<template>
  <div class="app-container">
    <el-form ref="form" :model="crud.order" :rules="rules" size="small" label-width="100px" style="margin-top: 20px">
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="单据编号">
            <el-input v-model="crud.order.code" disabled style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="业务日期">
            <el-date-picker
              v-model="crud.order.busDate"
              type="date"
              size="small"
              :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
              class="date-item"
              style="width: 100%;"
              format="yyyy - MM - dd"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="客户名称" prop="customerId">
            <div class="flex flex-row">
              <el-input v-model="crud.order.customerCode" disabled
                        style="width: 30%;" />
              <zSelect
                :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE' || (isDept && !crud.order.deptId)"
                ref="selectCustomer" isLast :value.sync="crud.order.customerId" :showName="crud.order.customerName"
                @getChange="getInfo" url="api/dropDown/basCustomerList" :params="customerParams" style="width: 70%;" />
            </div>
          </el-form-item>
        </el-col>

        <!--        <el-col :span="5">-->
        <!--          <el-form-item label="客户编码">-->
        <!--            <el-input v-model="crud.order.customerCode"  :disabled="crud.order.orderStatus==='PASS'"-->
        <!--                      style="width: 100%;"/>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="4">
          <el-form-item label="单据状态">
            <el-select v-model="crud.order.orderStatus" disabled class="edit-input" placeholder="请选择单据状态"
                       style="width: 100%;">
              <el-option
                v-for="(item,index) in dict.common_order_status"
                :key="index"
                v-if="item.seq>0"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="核销状态">
            <el-select v-model="crud.order.cancelStatus" disabled class="edit-input" placeholder="请选择核销状态"
                       style="width: 100%;">
              <el-option
                v-for="(item,index) in dict.common_cancel_status"
                :key="index"
                :label="item.label"
                :value="item.value "
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="业务员名称">
            <zSelect :value.sync="crud.order.userId" :showName="crud.order.userName" :label="crud.order.userName"
                     :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                     url="api/dropDown/sysUserList" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="部门">
            <zSelect :value.sync="crud.order.deptId" @change="deptChange" :showName="crud.order.deptName"
                     :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                     url="api/dropDown/childSysDeptList"
                     style="width:  100%" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="销售类型">
            <el-select v-model="crud.order.saleType" class="edit-input" @change="saleTypeChange"
                       :disabled="crud.order.isAccept === 1"
                       placeholder="请选择销售类型" style="width: 100%;">
              <el-option
                v-for="(item,index) in dict.t_sales_order_sale_type"
                :key="index"
                v-if="item.seq>0"
                :label="item.label"
                :value="item.value"

              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="单据类型" prop="type">
            <el-select v-model="crud.order.type" class="edit-input"
                       :disabled="this.crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                       placeholder="请选择单据类型" style="width: 100%;">
              <el-option
                v-for="(item,index) in dict.t_sales_order_type"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="联系人">
            <el-input v-model="crud.order.contactName"
                      :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                      placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="联系电话">
            <el-input v-model="crud.order.contactPhone"
                      :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                      placeholder="请输入" maxlength="11" oninput="value=value.replace(/[^\d]/g,'')" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="仓库名称" prop="warehouseId">
            <zSelect :value.sync="crud.order.warehouseId" :showName="crud.order.warehouseName"
                     :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                     url="api/dropDown/basWarehouseList" @change="setDetailWarehouse" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="拣货优先级">
            <el-input-number v-model="crud.order.pickSeq" style="width: 100%"
                             :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                             placeholder="拣货优先级" maxlength="11" oninput="value=value.replace(/[^\d]/g,'')"
                             show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="发货时间">
            <el-date-picker
              v-model="crud.order.sendDate"
              type="date"
              size="small"
              :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
              class="date-item"
              style="width: 100%;"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="所属二批">
            <z-select :value.sync="crud.order.scustomerId"
                      :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                      url="/api/dropDown/sCustomerList"
                      :params="{ids:crud.order.customerId}"
                      :showName="crud.order.scustomerName"></z-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="单据验证码">
            <el-input v-model="crud.order.verifyCode"
                      :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                      readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="送货地址">
            <el-input v-model="crud.order.deliveryAddress"
                      :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                      placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="地址">
            <el-input v-model="crud.order.address"
                      :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                      placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="跟车">
            <zSelect multiple :value.sync="crud.order.followUserIds" :showName="crud.order.followUserName"
                     style="width: 100%;" url="api/dropDown/sysUserList"
                     :disabled="this.crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="客户单号">
            <el-input v-model="crud.order.customerOrderCode"
                      :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                      style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="单据说明">
            <el-input v-model="crud.order.orderRemark"
                      :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                      style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="备注">
            <el-input v-model="crud.order.remark" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="4" class="flex flex-row">
          <el-form-item label="司机">
            <zSelect :value.sync="crud.order.driverUserIds" :showName="crud.order.driverUserName"
                     url="/api/dropDown/sysUserList"
                     :disabled="this.crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'"
                     style="width:  100%;"></zSelect>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="换货仓库">
            <el-input v-model="crud.order.exchangeWarehouseName" disabled style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="跟进文员">
            <el-input v-model="crud.order.clerkUserName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="客户分类">
            <el-input v-model="crud.order.customerTypeName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="5" v-permission="permission.onAccount">
          <el-form-item label="包厢">
            <z-select :value.sync="crud.order.hall"
                      :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE'  || !crud.order.isAdvance === 1"
                      url="/api/reservationBox"
                      labelKey="label"
                      valueKey="label"
                      :showName="crud.order.hall"></z-select>
          </el-form-item>
        </el-col>
        <el-col :span="5" v-permission="permission.onAccount">
          <el-form-item label="用餐日期">
            <el-date-picker
              v-model="crud.order.mealDate"
              type="date"
              size="small"
              :disabled="crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE' || !crud.order.isAdvance === 1"
              class="date-item"
              style="width: 100%;"
              format="yyyy - MM - dd"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="用餐时间" v-permission="permission.onAccount">
              <el-select v-model="crud.order.mealTime" class="edit-input" :disabled="this.crud.order.orderStatus==='PASS' || !crud.order.isAdvance === 1" placeholder="用餐时间"    style="width: 100%;">
                <el-option
                    v-for="(item,index) in mealTimeList"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="top_form">

      <crudOperation :permission="permission" v-if="isExceed!=='true'">
        <el-button
          slot="left"
          @click="addDetail"
          type="primary"
          :disabled="$route.params.id == 'add'"
          size="mini"
          v-permission="permission.add"
        >
          添加
        </el-button>
        <el-button
          slot="left"
          @click="toAdd"
          type="primary"
          size="mini"
          v-permission="permission.addDetail"
        >
          新增
        </el-button>
        <el-button
          slot="left"
          @click="submit()"
          type="primary"
          size="mini"
          v-permission="permission.add"
        >
          保存
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="$route.params.id=='null'"
          :loading="crud.passLoading"
          @click="pass('PASS',crud.order.id)"
          v-permission="permission.pass"
        >
          <!--        v-permission="permission.pass"-->
          审核
        </el-button>
        <!--        <el-button @click="cancel" type="primary" plain    size="mini">关闭</el-button>-->
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="success"
          @click="toSuperPass($route.params.id)"
          v-permission="permission.superPass"
          :disabled="$route.params.id == 'add' || crud.order.orderStatus==='PASS'"
        >
          超级审核
        </el-button>
        <!--        <el-button-->
        <!--          slot="left"-->
        <!--          class="filter-item"-->
        <!--          size="mini"-->
        <!--          type="success"-->
        <!--          :disabled="$route.params.id == 'add' || crud.order.orderStatus==='PASS'"-->
        <!--          @click="noPass($route.params.id)"-->
        <!--          v-permission="permission.ignorePromotionPass"-->
        <!--        >-->
        <!--          忽略促销审核-->
        <!--        </el-button>-->
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="primary"
          :disabled=" crud.order.orderStatus==='PASS'"
          @click="toAddList"
          v-permission="permission.batchAddDetail"
        >
          批量新增
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="primary"
          v-show="crud.order.type == '1' && crud.order.customerId && crud.order.orderStatus!=='PASS'"
          @click="toActivityGoods"
          v-permission="permission.salesGiftList"
        >
          活动商品
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          @click="crud.toCopy($route.params.id,'/redirect/sale/salesorderDetail')"
          :disabled="$route.params.id == 'add'"
          v-permission="permission.copy"
        >
          复制
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          @click="toAccept($route.params.id)"
          :disabled="$route.params.id == 'add' || crud.order.orderStatus ==='SAVE'"
          v-permission="permission.accept"
        >
          回单验收
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          @click="toUnAccept($route.params.id)"
          :disabled="$route.params.id == 'add' || crud.order.orderStatus ==='SAVE'"
          v-permission="permission.accept"
        >
          取消验收
        </el-button>


        <!--        <el-button-->
        <!--          slot="right"-->
        <!--          class="filter-item"-->
        <!--          size="mini"-->
        <!--          :disabled="$route.params.id == 'add' || crud.order.orderStatus==='PASS'"-->
        <!--          @click="crud.doDetailPassOrReject('INVALID')"-->
        <!--          v-permission="permission.invalid"-->
        <!--        >-->
        <!--          作废-->
        <!--        </el-button>-->
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          @click="isPromotion"
          :disabled="$route.params.id == 'add' || crud.order.orderStatus==='PASS'"
          v-permission="permission.split"
        >
          单据拆分
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          @click="showHistory(crud.selections[0])"
          :disabled="$route.params.id == 'add' || crud.order.orderStatus==='PASS'"
          v-permission="permission.copy"
        >
          单据记录
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          @click="handleCopyToReturn($route.params.id)"
          :disabled="$route.params.id == 'add' || crud.order.orderStatus!='PASS' & crud.order.orderStatus!='CLOSE'"
          v-permission="permission.copyToReturn"
        >
          复制为退货
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          @click="crud.toLockStock($route.params.id)"
          :disabled="$route.params.id == 'add' || crud.order.orderStatus==='PASS'"
          v-permission="permission.lockStock"
        >
          库存加锁
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          @click="crud.toUnLockStock($route.params.id)"
          :disabled="$route.params.id == 'add' || crud.order.orderStatus==='PASS'"
          v-permission="permission.lockStock"
        >
          库存解锁
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          @click="queryEmptyBox"
          v-if="crud.order.orderStatus !=='SAVE'"
          v-permission="permission.emptyBox"
        >
          查看空箱
        </el-button>
        <el-button
          slot="left"
          @click="submitAnd()"
          type="primary"
          :disabled="crud.order.orderStatus==='PASS'"
          size="mini"
          v-permission="permission.saveAndPass"
        >
          保存并审核
        </el-button>
        <el-button
          slot="left"
          @click="delAddRow"
          type="primary"
          :disabled="crud.order.orderStatus==='PASS'"
          size="mini"
          v-permission="permission.del"
        >
          删除
        </el-button>
        <el-button
          slot="left"
          @click="showPriceDialog = true"
          type="primary"
          size="mini"
          v-permission="permission.priceInfo"
        >
          价格信息
        </el-button>
        <el-button
          slot="right"
          size="mini"
          type="info"
          class="filter-item"
          :disabled="crud.order.orderStatus!=='PASS'&&crud.order.orderStatus!=='CLOSE'"
          @click="superReject"
          v-permission="permission.superReject"
        >
          一键反审
        </el-button>
        <el-button
          slot="left"
          @click="showHistoryDialog = true"
          type="primary"
          size="mini"
          v-permission="permission.salesHistory"
        >
          销售记录
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="warning"
          icon="el-icon-notebook-2"
          :disabled="crud.order.orderStatus=='PASS'"
          @click="volume()"
        >
          批量折扣
        </el-button>
        <el-button
          slot="right"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="printPd"
          :disabled="$route.params.id == 'add'"
        >打印
        </el-button>
        <el-button
          slot="right"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
          :disabled="$route.params.id == 'add'"
        >打印预览
        </el-button>

        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="$route.params.id=='null'"
          :loading="crud.passLoading"
          @click="crud.doDetailPassOrReject('INVALID',id)"

        >
          <!--        v-permission="permission.pass"-->
          作废
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          :loading="crud.rejectLoading"
          :disabled="$route.params.id=='null'"
          @click="crud.doDetailPassOrReject('RECOVER',id)"

        >
          <!--        v-permission="permission.reject"-->
          取消作废
        </el-button>
        <el-button
          slot="right"
          size="mini"
          type="info"
          class="filter-item"
          v-if="crud.order.isAccept==1 && crud.order.cancelStatus !=2"
          @click="superCancelShow = true"
          v-permission="permission.superCancel"
        >
          一键核销
        </el-button>
        <el-button
          slot="right"
          size="mini"
          type="info"
          class="filter-item"
          v-if="crud.order.isAccept== 1 && crud.order.cancelStatus !=0"
          @click="unCancel"
          v-permission="permission.superUnCancel"
        >
          一键反核销
        </el-button>
        <el-button
          slot="right"
          size="mini"
          type="info"
          class="filter-item"
          @click="showToRecycle"
          v-if="crud.order.orderStatus==='CLOSE' && crud.order.isRecycle == 0"
          v-permission="permission.recycle"
        >
          商品回收
        </el-button>
        <el-button
          slot="right"
          size="mini"
          type="info"
          class="filter-item"
          v-if="crud.order.orderStatus==='CLOSE' && crud.order.isRecycle == 1"
          @click="submitOnRecycle"
          v-permission="permission.unRecycle"
        >
          取消回收
        </el-button>
        <el-button
          slot="right"
          size="mini"
          type="info"
          class="filter-item"
          @click="appendSave"
          v-permission="permission.appendSave"
        >
          追加保存
        </el-button>
        <el-button
          slot="right"
          v-if="idDate"
          class="filter-item"
          size="mini"
          type="warning"
          @click="detailJump('up')"
        >上一页
        </el-button>
        <el-button
          slot="right"
          v-if="idDate"
          class="filter-item"
          size="mini"
          type="warning"
          @click="detailJump('down')"
        >下一页
        </el-button>
        <el-button
          slot="left"
          size="mini"
          type="info"
          class="filter-item"
          @click="settlement"
          v-permission="permission.settlement"
        >
          结算
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="success"
          @click="bomStockCheck"
          :disabled="crud.order.orderStatus!=='SAVE'"
          v-permission="permission.checkBomStock"
        >
          检查BOM库存
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="success"
          @click="setZeroPrice"
          v-permission="permission.setZeroPrice"
        >
          设置0单价
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="success"
          @click="resetDetailPrintStatus"
          :disabled="crud.selections.length === 0"
          v-permission="permission.resetDetailPrintStatus"
        >
          重置打印状态
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="$route.params.id == 'add' || crud.order.orderStatus==='PASS'"
          @click="dialogCheckMaterialWareHouse = true"
        >
          检查原料
        </el-button>
      </crudOperation>
      <div v-else>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="$route.params.id == 'add' || crud.order.orderStatus==='PASS'"
          @click="toSuperPass($route.params.id)"
          v-permission="permission.superPass"
        >
          超级审核
        </el-button>
      </div>
      <!--      <el-button @click="toCopy($event)">复制</el-button>-->
    </div>
    <!--    表格-->
    <!--表格渲染-->
    <div>
      <!--      <el-button-->
      <!--          class="filter-item"-->
      <!--          size="mini"-->
      <!--          type="primary"-->
      <!--          @click="addList"-->
      <!--      >-->
      <!--        新增-->
      <!--      </el-button>-->
    </div>
    <vue-context-menu :contextMenuData="contextMenuData"
                      @tableConfig="tableConfig"
                      @deletedata="deletedata"
                      @copy="copyElement"
                      @del="delAddRow"
                      @add="addGoodsRow"
    ></vue-context-menu>
    <el-dialog title="表格配置"
               :visible.sync="tableConfigShow"
               width="60%">
      <j-table-column-config :columns.sync="crud.header" @tabSave="head" @pit="pit" />
    </el-dialog>
    <el-dialog title="结算"
               :visible.sync="settlementShow"
               width="30%">
      <div>
        <el-form label-width="80px" ref="cancelForm" :model="cancel" :rules="cancelRules">
          <el-form-item label="已核销金额">
            <el-input disabled v-model="settlementData.order.cancelAmount"></el-input>
          </el-form-item>
          <el-form-item label="未核销金额">
            <el-input disabled v-model="settlementData.order.unCancelAmount"></el-input>
          </el-form-item>
          <el-form-item label="选择收款单">
            <table-select
              :tableColumns="
                  [
                  {prop:'busDate',label:'业务日期',width: '100'},
                  {prop:'receiptCode',label:'收款单号',width: '150'},
                  {prop:'taxAmount',label:'收款金额'},
                  {prop:'cancelAmount',label:'已核销金额'},
                  {prop:'unCancelAmount',label:'未核销金额'},
                  ]"
              labelKey="receiptCode"
              valueKey="receiptId"
              width="800"
              @change="deductionAmount"
              :value.sync="settlementForm.receiptIds"
              placeholder="请选择收款单"
              :params="{
                  customerId:settlementData.customerId
                }"
              url="api/salesOrder/settlement/draw"
            />
          </el-form-item>
          <el-form-item label="客户抵扣券" prop="tailAmount">
            <el-input type="number" disabled v-model="settlementData.customerDeductionAmount"></el-input>
          </el-form-item>
          <el-form-item label="尾差金额" prop="tailAmount">
            <el-input type="number" @change="deductionAmount" v-model="settlementForm.tailAmount"></el-input>
          </el-form-item>
          <el-form-item label="抵扣金额">
            <el-input type="number"
                      @change="setDeductionAmount"
                      v-model="settlementForm.deductionAmount"></el-input>
          </el-form-item>
          <el-form-item label="扣款金额">
            <el-input type="number"
                      disabled
                      @change="setDeductionAmount"
                      v-model="settlementForm.curCancelAmount"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="flex flex-reverse">
        <el-button @click="saveSettlement">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="核销"
               :visible.sync="superCancelShow"
               width="30%">
      <div>
        <el-form label-width="80px" ref="cancelForm" :model="cancel" :rules="cancelRules">
          <el-form-item label="银行" prop="bankId">
            <zSelect :value.sync="cancel.bankId" url="api/dropDown/basBankList" />
          </el-form-item>
          <el-form-item label="收款金额" prop="receiptAmount">
            <el-input type="number" v-model="cancel.receiptAmount"></el-input>
          </el-form-item>
          <el-form-item label="尾差金额" prop="tailAmount">
            <el-input type="number" v-model="cancel.tailAmount"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="cancel.receiptRemark"></el-input>
          </el-form-item>
          <el-form-item label="已核销金额">
            <el-input disabled v-model="crud.order.cancelAmount"></el-input>
          </el-form-item>
          <el-form-item label="未核销金额">
            <el-input disabled v-model="crud.order.unCancelAmount"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="flex flex-reverse">
        <el-button @click="saveCancel">确定</el-button>
      </div>
    </el-dialog>
    <u-table ref="tableParent" row-class-name="crud.tableRowClassName"
             v-if="isShowTable"
             @header-dragend="changeColWidth"
             @contextmenu.native="showMenu"
             :height="tableHeight"
             :data="crud.data"
             size="small" style="width: 100%;"
             show-summary
             sortable="custom"
             border
             use-virtual
             showBodyOverflow="title"
             showHeaderOverflow="title"
             :data-changes-scroll-top="false"
             @row-click="selectRow"
             :row-style="crud.rowClass"
             :row-class-name="crud.tableRowClassName"
             @selection-change="crud.selectionChangeHandler"
             @row-dblclick="switchRowIndex"
             highlight-current-row="highlight-current-row"
             :summary-method="summaryMethod"
             row-height="30"
    >
      <u-table-column type="selection" :selectable="isEmptyBox" width="60" />
      <el-table-column type="index" width="60" label="序号" />
      <el-table-column :sortable="item.sortable"
                       :label="columnLabel(item)"
                       v-if="item.visible"
                       v-for="(item,index) in crud.header"
                       :prop="item.prop"
                       :width="item.width">
        <template slot-scope="scope">
          <template>
            <span v-if="item.type == 1" :class="{red:crud.order.type === 2}">
                <span v-if="crud.order.type === 2">
                  <span v-if="red.includes(item.prop)">
                  -{{ scope.row[`${item.prop}`] }}
                  </span>
                  <span v-else>{{ scope.row[`${item.prop}`] }}</span>
                </span>
                <span v-else>
                  {{ scope.row[`${item.prop}`] }}
                </span>
            </span>
            <span v-else-if="item.type == 2"
                  :class="{red:crud.order.type === 2}">{{ parseTime(scope.row[`${item.prop}`]) }}</span>
            <span v-else-if="item.type == 3" :class="{red:crud.order.type === 2}">{{
                getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`)
              }}</span>
            <span v-else-if="item.type == 4" :class="{red:crud.order.type === 2}">
              <span v-if="item.prop == 'goodsName'" class="flex a-item">
                <span
                  :class="{'blue':(scope.row.isPromotion === 1),'green':scope.row.promotionGroupKey}"
                  v-if="scope.$index !== rowIndex || ((crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'|| scope.row.isOne === 0) && scope.row.id)"
                >
                  {{                    scope.row.goodsName                  }}
                </span>
                <!--                  <jtg-select-plus v-else ref="productRef"-->
                <!--                                   v-model="scope.row.goodsId"-->
                <!--                                   :type="crud.order.type"-->
                <!--                                   typeNum="2"-->
                <!--                                   :initValue="scope.row.goodsName"-->
                <!--                                   :customerId="crud.order.customerId"-->
                <!--                                   :buyChannel="crud.order.buyChannel"-->
                <!--                                   @remoteMethod="getValue($event,scope.$index)"-->
                <!--                                   @input="getInput($event,name,scope.$index)"-->
                <!--                                   @change="crud.productChange($event,scope)"-->
                <!--                                   url="productList"-->
                <!--                  />-->
                <el-input v-else placeholder="请输入商品" style="width: 100%" v-model="scope.row.goodsName" />
            </span>
            <span v-else-if="item.prop == 'discountRate'">
                <span
                  v-if="scope.$index !== rowIndex || ((crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'|| scope.row.isOne === 0) && scope.row.id)">{{
                    scope.row.discountRate
                  }}%</span>
                  <el-input v-if="scope.$index === rowIndex"
                            @input.native="crud.inuptCount(scope, 'discountRate')"
                            oninput="value=value.replace(/[^\d^\.]/g,'')"
                            maxlength="12"
                            v-model.lazy="scope.row.discountRate"
                            style="width: 100%"
                  >
                    <template slot="append">
                      %
                    </template>
                  </el-input>
            </span>
            <span v-else-if="item.prop == 'taxPrice'" style="display: flex;justify-content: center;align-items: center">
                 <span v-if="scope.$index !== rowIndex || crud.order.isAccept === 1" :class="highlight(scope.row)">{{
                     scope.row.taxPrice
                   }}</span>
                    <el-input oninput="value=value.replace(/[^\d^\.]/g,'')"
                              maxlength="12" @input="crud.inuptCount(scope, 'taxPrice')" v-else
                              v-model="scope.row.taxPrice"
                              placeholder="请输入内容"
                    />
            </span>
            <span v-else-if="item.prop == 'taxBoxPrice'"
                  style="display: flex;justify-content: center;align-items: center">
              <span v-if="scope.$index !== rowIndex || crud.order.isAccept === 1" :class="highlight(scope.row)">{{
                  scope.row.taxBoxPrice
                }}</span>
                <el-input v-else oninput="value=value.replace(/[^\d^\.]/g,'')"
                          maxlength="12" @input.native="crud.inuptCount(scope, 'taxBoxPrice')"
                          v-model="scope.row.taxBoxPrice"
                          placeholder="请输入内容">
                </el-input>
            </span>
            <span v-else-if="item.prop == 'goodsCount'"
                  style="display: flex;justify-content: center;align-items: center">
              <span
                v-if="scope.$index !== rowIndex  || ((crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'|| scope.row.isOne === 0) && scope.row.id)"><span
                v-if="crud.order.type == 2">-</span>{{ scope.row.goodsCount }}</span>
              <el-input v-else v-model="scope.row.goodsCount" @input="couputedGoodsUnitCount(scope.row)"
                        @change="changGoodsCount(scope.row)"
                        placeholder="请输入内容"></el-input>
            </span>
            <span v-else-if="item.prop == 'boxNum'" style="display: flex;justify-content: center;align-items: center">
            <span
              v-if="scope.$index !== rowIndex  || ((crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'|| scope.row.isOne === 0) && scope.row.id)"><span
              v-if="crud.order.type == 2">-</span>{{ scope.row.boxNum || 0 }}{{ scope.row.boxUnitName }}</span>
            <el-input v-else
                      @input.native="crud.inuptCount(scope, 'boxNum')"
                      @change="changGoodsCount(scope.row)"
                      maxlength="12"
                      v-model="scope.row.boxNum"
                      style="width:50%;float: left">
              <div slot="suffix" style="height: 100%;font-size: 15px;color: black"
                   class="flex a-item j-content">{{ scope.row.boxUnitName }}</div>
            </el-input>
              <span
                v-if="scope.$index !== rowIndex || ((crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'|| scope.row.isOne === 0) && scope.row.id)">{{
                  scope.row.mainNum || 0
                }}{{ scope.row.mainUnitName }}</span>
                <el-input v-else
                          @input.native="crud.inuptCount(scope, 'mainNum')"
                          maxlength="12"
                          v-model="scope.row.mainNum"
                          @change="changGoodsCount(scope.row)"
                          style="width:50%;float: right">
                  <div slot="suffix" style="height: 100%;font-size: 15px;color: black"
                       class="flex a-item j-content">{{ scope.row.mainUnitName }}</div>%
                </el-input>
              </span>
              <span v-else-if="item.prop == 'warehouseName'"
                    style="display: flex;justify-content: center;align-items: center">
                <span
                  v-if="scope.$index !== rowIndex || ((crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'|| scope.row.isOne === 0) && scope.row.id)"
                >{{
                    scope.row.warehouseName
                  }}</span>
                <zSelect v-else v-model="scope.row.warehouseId" :showName="scope.row.warehouseName" class="edit-input"
                         @change="crud.setProduct($event,scope,'warehouseName')" :value.sync="scope.row.warehouseId"
                         url="api/dropDown/basWarehouseList"/>
              </span>
              <span v-else-if="item.prop == 'locationName'">
               <span
                 v-if="scope.$index !== rowIndex || ((crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'|| scope.row.isOne === 0) && scope.row.id)">{{
                   scope.row.storehouseName
                 }}</span>
                <zSelect v-else :value.sync="scope.row.locationId" :showName="scope.row.locationName"
                         :params="{warehouseId:scope.row.warehouseId}" url="api/dropDown/basLocationList"
                         style="width: 100%;" />
              </span>
              <span v-else-if="item.prop == 'storehouseName'">
               <span
                 v-if="scope.$index !== rowIndex || ((crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'|| scope.row.isOne === 0) && scope.row.id)">{{
                   scope.row.storehouseName
                 }}</span>
                <zSelect v-else :value.sync="scope.row.storehouseId" :showName="scope.row.storehouseName"
                         @change="crud.setProduct($event,scope,'storehouseName')"
                         :params="{warehouseId:scope.row.warehouseId}" url="api/dropDown/basStorehouseList"
                         style="width: 100%;" />
              </span>
              <span v-else-if="item.prop == 'goodsTagName'"
                    style="display: flex;justify-content: center;align-items: center">
              <span
                v-if="scope.$index !== rowIndex || ((crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'|| scope.row.isOne === 0) && scope.row.id)">{{
                  scope.row.goodsTagName
                }}</span>
                <zSelect v-else :value.sync="scope.row.goodsTagId" :params="{sort:'code asc'}"
                         :showName="scope.row.goodsTagName" :label="scope.row.goodsTagName"
                         @change="crud.setProduct($event,scope,'goodsTagName')" url="api/dropDown/basGoodsTagList"
                         style="width: 100%;" />
              </span>
            <span v-else-if="item.prop == 'remark'">
          <span v-if="scope.$index !== rowIndex|| scope.row.isOne === 0">{{ scope.row.remark }}</span>
          <el-input v-else v-model="scope.row.remark" type="textarea" style="width: 100%;" />
            </span>
              <span v-else-if="item.prop == 'usableNum'">
                <div v-if="scope.$index !== rowIndex|| scope.row.isOne === 0"
                     style="display: flex;justify-content: center;align-items: center;">{{ scope.row.usableNum }}</div>
              </span>
            <span v-else-if="item.prop == 'usableBoxNum'"
                  style="display: flex;justify-content: center;align-items: center">
                <span>{{ scope.row.usableBoxNum || 0 }}{{ scope.row.boxUnitName }}</span>
                <span>{{ scope.row.usableMainNum || 0 }}{{ scope.row.mainUnitName }}</span>
            </span>
            <span v-else-if="item.prop == 'fuckNum'">
                <span>{{ scope.row.acceptBoxNum || 0 }}{{ scope.row.boxUnitName }}</span>
                <span>{{ scope.row.acceptMainNum || 0 }}{{ scope.row.mainUnitName }}</span>
            </span>
            <span v-else-if="item.prop == 'actualAcceptBoxNum;'">
                <span>{{ scope.row.actualAcceptBoxNum || 0 }}{{ scope.row.boxUnitName }}</span>
                <span>{{ scope.row.actualAcceptMainNum || 0 }}{{ scope.row.mainUnitName }}</span>
            </span>
            <span v-else-if="item.prop == 'billTaxPrice'"
                  style="display: flex;justify-content: center;align-items: center">

                 <span
                   v-if="scope.$index !== rowIndex  || ((crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'|| scope.row.isOne === 0) && scope.row.id)">{{
                     scope.row.billTaxPrice
                   }}</span>
                    <el-input oninput="value=value.replace(/[^\d^\.]/g,'')"
                              maxlength="12" @input="computedBill(scope.row, 'billTaxPrice')" v-else
                              v-model="scope.row.billTaxPrice"
                              placeholder="请输入内容"
                    ></el-input>
            </span>
            <span v-else-if="item.prop == 'billTaxBoxPrice'"
                  style="display: flex;justify-content: center;align-items: center">
                 <span
                   v-if="scope.$index !== rowIndex  || ((crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'|| scope.row.isOne === 0) && scope.row.id)">{{
                     scope.row.billTaxBoxPrice
                   }}</span>
                    <el-input oninput="value=value.replace(/[^\d^\.]/g,'')"
                              maxlength="12" @input="computedBill(scope.row, 'billTaxBoxPrice')" v-else
                              v-model="scope.row.billTaxBoxPrice"
                              placeholder="请输入内容"
                    ></el-input>
            </span>
            <span v-else-if="item.prop == 'billTaxAmount'"
                  style="display: flex;justify-content: center;align-items: center">
                 <span
                   v-if="scope.$index !== rowIndex  || ((crud.order.orderStatus==='PASS'||crud.order.orderStatus==='CLOSE'|| scope.row.isOne === 0) && scope.row.id)">{{
                     Number(scope.row.billTaxAmount).toFixed(2)
                   }}</span>
                    <el-input oninput="value=value.replace(/[^\d^\.]/g,'')"
                              maxlength="12" @input="computedBill(scope.row, 'billTaxAmount')" v-else
                              v-model="scope.row.billTaxAmount"
                              placeholder="请输入内容"
                    ></el-input>
            </span>
            <span v-else-if="item.prop == 'taxAmount'" class="flex a-item j-content">
              <span v-if="scope.$index !== rowIndex || crud.order.isAccept === 1"><span
                v-if="crud.order.type == 2">-</span>{{ Number(scope.row.taxAmount).toFixed(2) }}</span>
                <el-input v-else oninput="value=value.replace(/[^\d^\.]/g,'')"
                          maxlength="12" @input.native="crud.inuptCount(scope, 'taxAmount')"
                          v-model="scope.row.taxAmount"
                          placeholder="请输入内容">
                </el-input>
            </span>
            </span>
          </template>
        </template>
      </el-table-column>
    </u-table>

    <el-dialog
      title="查看空箱"
      :visible.sync="isEmptyBoxShow"
    >
      <el-table
        height="500px"
        border
        show-summary
        :data="emptyBoxList"
        style="width: 100%"
      >
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column prop="goodsCode" label="商品编码"></el-table-column>
        <el-table-column prop="goodsName" label="商品名称"></el-table-column>
        <el-table-column prop="barcode" label="条形码"></el-table-column>
        <el-table-column prop="mainUnitName" label="单位"></el-table-column>
        <el-table-column prop="packageType" label="包装类型">
          <template slot-scope="scope">
            {{ dict.label.t_bas_goods_package_type[scope.row.packageType] }}
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="goodsCount"></el-table-column>
        <el-table-column label="价格" prop="taxPrice"></el-table-column>
        <el-table-column label="金额" prop="taxAmount"></el-table-column>
        <el-table-column label="备注" prop="remark"></el-table-column>
      </el-table>
    </el-dialog>

    <j-dialog
      title="检查bom"
      :visible.sync="lackBomShow"
      isMask
      style="width: 80vw;"
    >
      <goods-demand :warehouse-id="checkMaterialWareHouse.id" @close="lackBomShow = false" :sales-order-ids="crud.order.id"/>
    </j-dialog>
    <!--检查库存仓库仓库-->
    <j-dialog is-mask title="检查仓库" style="width: 500px" :visible.sync="dialogCheckMaterialWareHouse">
      <el-form  label-width="80px" size="small">
        <el-form-item label="检查仓库" >
          <zSelect :value.sync="checkMaterialWareHouse.id" @change="checkMaterialWareHouse = $event" :showName="checkMaterialWareHouse.name" url="api/dropDown/basWarehouseList"/>
        </el-form-item>
      </el-form>
      <div class="dialog-footer flex flex-reverse">
        <el-button @click="dialogCheckMaterialWareHouse = false">取 消</el-button>
        <el-button type="primary" @click="showLackBom()">确 定</el-button>
      </div>
    </j-dialog>
    <j-dialog
      title="请选择打印模板"
      :visible.sync="crud.printConfig.pringDialog"
      style="width: 20%"
      isMask
    >
      <jPrintConfig groupId="salesOrder"
                    v-if="crud.printConfig.pringDialog"
                    @getPrintId="crud.detailedPrint"
                    :isPreview="crud.printConfig.isPreview"
      ></jPrintConfig>
    </j-dialog>
    <!--批量新增弹窗-->
    <el-dialog :close-on-click-modal="false" title="商品新增"
               :visible.sync="showAddBatchDialog" append-to-body width="100vw">
      <add-batch v-if="showAddBatchDialog" :showAddBatchDialog.sync="showAddBatchDialog" :list="detailList"
                 :params="{customerId:crud.order.customerId,type:crud.order.type==1?'SALE':'SALE_RETURN',
                 warehouseId:crud.order.warehouseId
                 }"
                 :saleType="crud.order.saleType"
                 :type="crud.order.type"
                 @change="afterChangeGoods"></add-batch>
    </el-dialog>

    <!--价格信息弹窗-->
    <j-dialog title=""
              style="width: 1000px"
              v-show="showPriceDialog"
              :visible.sync="showPriceDialog"
    >
      <price-detail
        :tableData="priceList"
        :customerId="crud.order.customerId"
        :showAddBatchDialog.sync="showPriceDialog"
        @change="afterChangeGoods"></price-detail>
    </j-dialog>
    <!--    <el-dialog :close-on-click-modal="false" title="价格信息"-->
    <!--               v-dialogDrag-->
    <!--               :modal="false"-->
    <!--               :visible.sync="showPriceDialog" append-to-body width="40vw">-->
    <!--      <price-detail-->

    <!--        :tableData="priceList" :customerId="crud.order.customerId"   :showAddBatchDialog.sync="showPriceDialog"-->
    <!--                    @change="afterChangeGoods"></price-detail>-->
    <!--    </el-dialog>-->
    <!--活动商品弹窗-->
    <el-dialog :close-on-click-modal="false" title="活动商品"
               :visible.sync="toActivityShow" append-to-body width="80vw">
      <j-goods :parentData="crud.data" :toActivityShow="toActivityShow" @addGoods="addGoods"
               :customerId="crud.order.customerId"></j-goods>
    </el-dialog>

    <!--商品拆分弹窗-->
    <el-dialog :close-on-click-modal="false" title="拆分商品"
               :visible.sync="toSplitShow" append-to-body width="80vw">
      <el-table
        :data="crud.selections"
        style="width: 100%"
        border
        ref="goodsTable"
        height="500"
      >
        <el-table-column type="selection" width="60" />
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column
          prop="goodsCode"
          label="商品编码"
        >
        </el-table-column>
        <el-table-column
          prop="goodsName"
          label="商品名称"
        >
        </el-table-column>
        <el-table-column
          prop="barcode"
          label="条形码"
        >
        </el-table-column>
        <el-table-column
          prop="goodsCount"
          label="单据数量"
        >
        </el-table-column>
        <el-table-column
          prop="goodsCount"
          label="单据辅数量"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.boxNum }}{{ scope.row.boxUnitName }}</span>
            <span>{{ scope.row.mainNum }}{{ scope.row.mainUnitName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="boxNum"
          label="拆分辅数量"
          width="400px"
        >
          <template slot-scope="scope">
            <el-input
              @change="inputCount(scope.row, 'splitBoxNum')"
              maxlength="12"
              v-model="scope.row.splitBoxNum"
              style="width: 45%;float: left">
              <template slot="append">{{ scope.row.boxUnitName }}</template>
            </el-input>
            <el-input
              @change="inputCount(scope.row, 'splitMainNum')"
              maxlength="12"
              v-model="scope.row.splitMainNum"
              style="width: 45%;float: right">
              <template slot="append">{{ scope.row.mainUnitName }}</template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="splitGoodsCount"
          label="拆分数量"
        >
          <template slot-scope="scope">
            <el-input
              maxlength="12"
              v-model="scope.row.splitGoodsCount"
              @change="inputCount(scope.row,'splitGoodsCount')"
              oninput="value=value.replace(/[^\d^\.]/g,'')"
              style="width: 100%;float: left">
            </el-input>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 80px">
        <el-button type="primary" style="position: absolute;right: 20px;bottom: 20px"
                   @click="submitSplit"
        >提交
        </el-button>
      </div>
    </el-dialog>
    <!--单据回收商品弹窗-->
    <el-dialog :close-on-click-modal="false" title="商品回收"
               :visible.sync="toRecycleShow" append-to-body width="80vw">
      <el-table
        :data="recycleData"
        style="width: 100%"
        border
        ref="goodsTable"
        height="500"
        v-loading="recycleLoading"
      >
        <el-table-column type="selection" width="60" />
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column
          prop="goodsCode"
          label="商品编码"
        >
        </el-table-column>
        <el-table-column
          prop="goodsName"
          label="商品名称"
        >
        </el-table-column>
        <el-table-column
          prop="barcode"
          label="条形码"
        >
        </el-table-column>
        <el-table-column
          prop="goodsCount"
          label=原数量"
        >
        </el-table-column>
        <el-table-column
          prop="goodsCount"
          label="原辅数量"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.boxNum }}{{ scope.row.boxUnitName }}</span>
            <span>{{ scope.row.mainNum }}{{ scope.row.mainUnitName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="acceptGoodsCount"
          label=发货数量"
        >
        </el-table-column>
        <el-table-column
          prop="goodsCount"
          label="发货辅数量"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.acceptBoxNum }}{{ scope.row.boxUnitName }}</span>
            <span>{{ scope.row.acceptMainNum }}{{ scope.row.mainUnitName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="recycleGoodsCount"
          label="回收辅数量"
          width="400px"
        >
          <template slot-scope="scope">
            <el-input
              @change="inputCount(scope.row, 'recycleBoxNum')"
              maxlength="12"
              v-model="scope.row.recycleBoxNum"
              style="width: 45%;float: left">
              <template slot="append">{{ scope.row.boxUnitName }}</template>
            </el-input>
            <el-input
              @change="inputCount(scope.row, 'recycleMainNum')"
              maxlength="12"
              v-model="scope.row.recycleMainNum"
              style="width: 45%;float: right">
              <template slot="append">{{ scope.row.mainUnitName }}</template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="recycleGoodsCount"
          label="回收数量"
        >
          <template slot-scope="scope">
            <el-input
              maxlength="12"
              v-model="scope.row.recycleGoodsCount"
              @change="inputCount(scope.row,'recycleGoodsCount')"
              oninput="value=value.replace(/[^\d^\.]/g,'')"
              style="width: 100%;float: left">
            </el-input>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 80px">
        <el-button type="primary" style="position: absolute;right: 20px;bottom: 20px"
                   @click="submitRecycle"
        >提交
        </el-button>
      </div>
    </el-dialog>
    <!--销售记录弹窗-->
    <j-dialog title="销售记录"
              v-dialogDrag
              :visible.sync="showHistoryDialog"
              style="width: 80%"
    >
      <history :data="current" :historyDialog="showHistoryDialog" :customerId="crud.order.customerId"
               :showAddBatchDialog.sync="showHistoryDialog" @change="afterChangeGoods"></history>
    </j-dialog>

    <!--选择商品-->
    <j-dialog title="选择商品"
              :visible.sync="showQueryGoods"
              isMask
              style="width: 80%;overflow: auto"
    >
      <div>
        <j-goods-select v-if="(crud.order.orderStatus==='PASS'|| crud.order.orderStatus==='CLOSE') && showQueryGoods"
                        @addPromotionList="addPromotionList" @diaLogGoodsChange="changeGoods"
                        :customerId="crud.order.customerId" type="SALE" @closeDialog="closeDialog"
                        :queryGoods="queryGoods" />
        <promotion-goods-select v-else @addPromotionList="addPromotionList" @diaLogGoodsChange="changeGoods"
                                :customerId="crud.order.customerId" :type="crud.order.type===1?'SALE':'SALE_RETURN'"
                                @closeDialog="closeDialog" v-if="showQueryGoods"
                                :params="{
                                    warehouseId:crud.order.warehouseId
                                }"
                                :queryGoods="queryGoods"></promotion-goods-select>
      </div>
    </j-dialog>

    <!--换货仓库-->
    <j-dialog is-mask title="换货仓库" style="width: 500px" :visible.sync="dialogChangeWarehouse">
      <el-form  :model="form" label-width="80px" size="small">
        <el-form-item label="换货仓库" prop="exchangeWarehouseName">
          <zSelect :value.sync="form.exchangeWarehouseId" :showName="form.exchangeWarehouseName" url="api/dropDown/basWarehouseList"/>
        </el-form-item>
      </el-form>
      <div class="dialog-footer flex flex-reverse">
        <el-button @click="dialogChangeWarehouse = false">取 消</el-button>
        <el-button type="primary" @click="ChangeWarehouse()">确 定</el-button>
      </div>
    </j-dialog>

    <el-dialog title="打印预览"
               destroy-on-close1
               v-dialogDrag
               close-on-press-escape
               :visible.sync="showPdf" append-to-body width="50vw">
      <j-pdf :src="pdfSrc"></j-pdf>
    </el-dialog>
    <!--表单组件-->
    <el-dialog :before-close="cancelCU" :close-on-click-modal="false" title="退货"
               :visible.sync="isCopyToReturn" append-to-body width="500px">
      <el-form   :rules="rules" label-width="80px" size="small">
        <el-form-item label="仓库">
          <zSelect :value.sync="form.warehouseId" :showName="form.warehouseId" url="api/dropDown/basWarehouseList" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancelCU">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="crud.toCopyToReturnPlus(form,$route.params.id)">
          确认
        </el-button>
      </div>
    </el-dialog>


    <!--    批量折扣-->
    <el-dialog title="批量折扣"
               :visible.sync="isVolume"
               width="25%">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="按品牌折扣" name="1">
          <el-table
            border
            :data="goodsBrandDiscountList"
            style="width: 100%">
            <el-table-column
              prop="goodsBrandName"
              label="品牌名称"
            >
            </el-table-column>
            <el-table-column
              prop="discountRate"
              label="折扣率"
            >
              <template slot-scope="scope">
                <el-input-number :step="0.1" :min="0"  v-model="scope.row.discountRate" style="width: 100%;"/>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="按分类折扣" name="2">
          <el-table
            border
            :data="goodsTypeDiscountList"
            style="width: 100%">
            <el-table-column
              prop="goodsTypeName"
              label="商品分类"
            >
            </el-table-column>
            <el-table-column
              prop="discountRate"
              label="折扣率"
              width="180">
              <template slot-scope="scope">
                <el-input-number :step="0.1" :min="0"  v-model="scope.row.discountRate" style="width: 100%;"/>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="整单折扣" name="3">
          <el-table
            border
            :data="goodsDiscountList"
            style="width: 100%">

            <el-table-column
              prop="discountRate"
              label="整单折扣"
            >
              <template slot-scope="scope">
                <el-input-number :step="0.1" :min="0"  v-model="scope.row.discountRate" style="width: 100%;"/>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancelCUDis">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="handleDisCl()">确认</el-button>
      </div>
    </el-dialog>
    <div id="contextmenu"
         v-show="menuVisible"
         class="menu">
      <div class="contextmenu__item" v-if="crud.order.orderStatus!=='PASS'"
           @click="delAddRowPlus(CurrentRow)">删除
      </div>
      <div v-if="$route.params.id != 'add'" class="contextmenu__item"
           @click="showPriceDetail(CurrentRow)">价格信息
      </div>
      <div v-if="$route.params.id != 'add'" class="contextmenu__item"
           @click="showHistory(CurrentRow)">历史销售记录
      </div>
    </div>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import crudBasSaleSystem, { checkMaterial } from '@/api/erp/salesOrder'
import crudSalesOrder, { batchRemoveDetail, checkCustomerIsExceed } from '@/api/erp/salesOrder'
import { getSaleOrderDetail, split } from '@/api/erp/salesOrderDetail'
import crudOperation from '@crud/CRUD.operation'
import addBatch from '@/components/addBatch/addBatch'
import priceDetail from '@/views/erp/salesOrder/priceDetail'
import history from '@/views/erp/salesOrder/history'
import CRUD, { crud, form, header, presenter } from '@crud/crud'
import jtgSelectPlus from '@/components/select/JtgSelectPlusSale'
import { Notification } from 'element-ui'
import jPrintConfig from '../../../components/jPrintConfig/jPrintConfig'
import {
  batchDiscount, checkBomStock,
  emptyBox,basWarehouseList,
  getBatchDiscountInfo,
  recycle, resetDetailPrint,
  settlementDraw,
  settlementSave
} from '../../../api/erp/salesOrder'
import { salesDetailKey } from '@/utils/key'
import { tablemixins } from '@/mixins/tablemixins'
import jTableColumnConfig from '@/components/jTableColumnConfig/jTableColumnConfig'
import { getHeaderProperties } from '@/api/erp/headerProperties'
import jGoods from '@/components/jGoods/jGoods'
import jDialog from '@/components/jDialog/jDialog'
import jGoodsSelect from '@/components/jGoodsSelect/jGoodsSelect'
import Vue from 'vue'
import promotionGoodsSelect from '@/components/promotionGoodsSelect/promotionGoodsSelect'
import { get as getDictDetail } from '@/api/system/dictDetail'
import { getGoodsTagList } from '../../../api/erp/basGoodsTag'
import goodsDemand from '@/components/goodsDemand/index.vue'
const defaultCrud = CRUD({
  title: '销售单明细',
  url: 'api/salesOrder/detail',
  name: 'salesOrderDetail',
  sort: 't.seq,asc',
  params() {
    const href = location.href.split('/')
    if (href[5].includes('copyId')) {
      return {
        id: 0
      }
    } else {
      return {
        id: href[href.length - 1].split('?')[0] == 'add' ? 0 : href[href.length - 1].split('?')[0], page: 0, size: 999
      }
    }
  },
  crudMethod: { ...crudSalesOrder },
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: false,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: true,
    downloadDetail: false,
    recover: false,
    invalid: false,
    print: false,
    printDetail: false,
    exportDetail: false
  }
})
const defaultForm = {
  id: null,
  code: null,
  name: null,
  type: 1,
  saleType: 1,
  busDate: null,
  sourceType: null,
  sourceId: null,
  sourceCode: null,
  serialNumber: null,
  customerOrderCode: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  isContact: 1,
  deptId: null,
  deptCode: null,
  deptName: null,
  userId: null,
  userCode: null,
  userName: null,
  warehouseId: null,
  warehouseCode: null,
  warehouseName: null,
  count: null,
  boxCount: null,
  taxAmount: null,
  noTaxAmount: null,
  tax: null,
  discountAmount: null,
  acceptBoxCount: null,
  acceptTaxAmount: null,
  acceptNoTaxAmount: null,
  acceptTax: null,
  cancelAmount: null,
  unCancelAmount: null,
  receiveDate: null,
  carId: null,
  carCode: null,
  carName: null,
  loadId: null,
  loadCode: null,
  loadTime: null,
  driverUserId: null,
  driverUserCode: null,
  driverUserName: null,
  followUserId: null,
  followUserIds: null,
  followUserCode: null,
  followUserName: null,
  printStatus: null,
  printCount: null,
  customerAreaId: null,
  customerAreaCode: null,
  customerAreaName: null,
  customerTypeId: null,
  customerTypeCode: null,
  customerTypeName: null,
  pCustomerId: null,
  pCustomerCode: null,
  pCustomerName: null,
  mCustomerId: null,
  mCustomerCode: null,
  mCustomerName: null,
  sCustomerId: null,
  sCustomerCode: null,
  sCustomerName: null,
  seq: null,
  orderStatus: null,
  acceptStatus: '0',
  cancelStatus: '0',
  remark: null,
  usableNum: null,
  orderRemark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  closeUserId: null,
  closeUserCode: null,
  closeUserName: null,
  closeTime: null,
  deliveryAddress: null,
  scustomerId: null,
  idList: [],
  exchangeWarehouseId: null,
  hall:null
}
const copyFrom = Object.assign({}, defaultForm)

export default {
  name: 'salesOrderDetail',
  components: {
    jGoods,
    Treeselect,
    addBatch,
    priceDetail,
    history,
    crudOperation,
    jtgSelectPlus,
    jPrintConfig,
    jTableColumnConfig,
    jDialog,
    jGoodsSelect,
    promotionGoodsSelect,
    goodsDemand
  },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(), salesDetailKey, tablemixins],
  dicts: ['common_cancel_status',
    'common_order_status',
    'common_yes_or_no',
    't_sales_order_type',
    't_sales_order_source_type',
    't_sales_order_sale_type',
    't_buy_order_buy_channel',
    't_sales_promotion_type',
    't_bas_goods_package_type',
    't_bas_unit_type',
    't_sales_order_save_order_status_is_allow_print',
    't_bas_customer_is_contact'
  ],
  data() {
    return {
      WarehouseList:[],
      sales_order_type_list: [{
        label: '销售订单',
        value: 'SALE'
      }, {
        label: '销售退货单',
        value: 'SALE_RETURN'
      }],
      settlementShow:false,
      toRecycleShow: false,
      recycleData: [],
      showName: {
        id: null,
        name: null
      },
      lackingComponentList:[],
      lackingMaterialList:[],
      settlementData:{
        customerDeductionAmount:0,
        customerId:'',
        order:{}
      },
      settlementForm:{
        deductionAmount:0,
        receiptIds:'',
        curCancelAmount:0,
        tailAmount:0,
      },
      customerParams: {
        isContact: '0,2',
        sort: 'code asc'
      },
      activeName: '1',
      red: ['goodsCount', 'boxCount', 'taxAmount', 'noTaxAmount', 'tax', 'discountAmount', 'acceptGoodsCount', 'acceptBoxCount', 'oldTaxAmount', 'oldNoTaxAmount', 'oldTax', 'acceptTaxAmount', 'acceptNoTaxAmount', 'acceptTax', 'boxNum', 'mainNum', 'acceptBoxNum', 'acceptMainNum', 'cancelAmount', 'unCancelAmount'],
      // red:['acceptBoxCount','goodsCount','boxCount','boxCount','taxAmount','noTaxAmount','discountAmount','acceptTaxAmount','acceptNoTaxAmount',],
      isTheCache: false,
      depts: [],
      typeList: [],
      areaList: [],
      mealTimeList:[{label:"午宴",value:'0'},{label:"晚宴",value:'1'}],
      contextMenuData: {
        menuName: 'table',
        axis: {
          x: null,
          y: null
        },
        // 菜单选项
        menulists: [
          {
            fnHandler: 'tableConfig', // 绑定事件
            icoName: 'el-icon-setting', // icon图标
            btnName: '表格设置' // 菜单名称
          },
          {
            fnHandler: 'copy', // 绑定事件
            icoName: 'el-icon-edit', // icon图标
            btnName: '复制' // 菜单名称
          },
          {
            fnHandler: 'add', // 绑定事件
            icoName: 'el-icon-edit', // icon图标
            btnName: '新增' // 菜单名称
          },
          {
            fnHandler: 'del', // 绑定事件
            icoName: 'el-icon-edit', // icon图标
            btnName: '删除' // 菜单名称
          }

        ]
      },
      sCustomerList: [],
      isVolume: false,
      rules: {
        warehouseId: [
          { required: true, message: '请选择仓库', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择单据类型', trigger: 'blur' }
        ],
        // customerId: [
        //   {required: true, message: '请选择客户', trigger: 'blur'}
        // ],
        buyChannel: [
          { required: true, message: '请选择采购渠道', trigger: 'blur' }
        ]
      },
      priceList: null,
      permission: {
        add: ['admin', 'salesOrder:add'],
        edit: ['admin', 'salesOrder:edit'],
        del: ['admin', 'salesOrder:del'],
        import: ['admin', 'salesOrder:import'],
        export: ['admin', 'salesOrder:export'],
        copy: ['admin', 'salesOrder:copy'],
        upload: ['admin', 'salesOrder:upload'],
        download: ['admin', 'salesOrder:download'],
        pass: ['admin', 'salesOrder:pass'],
        reject: ['admin', 'salesOrder:reject'],
        superReject: ['admin', 'salesOrder:reject'],
        closed: ['admin', 'salesOrder:closed'],
        invalid: ['admin', 'salesOrder:invalid'],
        stop: ['admin', 'salesOrder:stop'],
        recover: ['admin', 'salesOrder:recover'],
        history: ['admin', 'salesOrder:history'],
        checkBomStock:['admin','salesOrder:checkBomStock'],
        accept: ['admin', 'salesOrder:accept'],
        unAccept: ['admin', 'salesOrder:unAccept'],
        lockStock: ['admin', 'salesOrder:lockStock'],
        superPass: ['admin', 'salesOrder:superPass'],
        ignorePromotionPass: ['admin', 'salesOrder:ignorePromotionPass'],
        saveAndPass: ['admin', 'salesOrder:saveAndPass'],
        priceInfo: ['admin', 'salesOrder:priceInfo'],
        salesHistory: ['admin', 'salesOrder:salesHistory'],
        exportDetail: ['admin', 'salesOrder:exportDetail'],
        print: ['admin', 'salesOrder:print'],
        addDetail: ['admin', 'salesOrder:addDetail'],
        batchAddDetail: ['admin', 'salesOrder:batchAddDetail'],
        salesGiftList: ['admin', 'salesOrder:salesGiftList'],
        split: ['admin', 'salesOrder:split'],
        copyToReturn: ['admin', 'salesOrder:copyToReturn'],
        emptyBox: ['admin', 'salesOrder:emptyBox'],
        superCancel: ['admin', 'salesOrder:superCancel'],
        superUnCancel: ['admin', 'salesOrder:superUnCancel'],
        recycle: ['admin', 'salesOrder:recycle'],
        unRecycle: ['admin', 'salesOrder:unRecycle'],
        append: ['admin', 'salesOrder:append'],
        appendSave: ['admin', 'salesOrder:appendSave'],
        settlement: ['admin', 'salesOrder:settlement'],
        onAccount:['admin', 'salesOrder:onAccount'],
        setZeroPrice:['admin', 'salesOrder:setZeroPrice'],
        resetDetailPrintStatus:['admin', 'salesOrder:setZeroPrice'],
      },
      id: 0,
      recycleLoading: false,
      emptyList: [2, 3, 4, 5, 7],
      toActivityShow: false,
      showAddBatchDialog: false,
      detailList: [],
      menuVisible: false,
      form: JSON.parse(JSON.stringify(defaultForm)),
      showPriceDialog: false,
      showHistoryDialog: false,
      current: null,//选中操作的内容
      isCopyToReturn: false,
      CurrentRow: null,
      isEmptyBoxShow: false,
      emptyBoxList: [],
      detailName: 'salesOrder_add',
      toSplitShow: false,
      giftIds: [],
      user: {},
      goodsBrandDiscountList: [],
      goodsDiscountList: [],
      goodsTypeDiscountList: [],
      queryGoods: {
        index: null,
        keyword: ''
      },
      showQueryGoods: false,
      superCancelShow: false,
      cancel: {
        bankId: null,
        receiptAmount: null,
        tailAmount: null,
        receiptRemark: null
      },
      isDept: false,
      cancelRules: {
        bankId: [
          { required: true, message: '请选择银行', trigger: 'blur' }
        ],
        receiptAmount: [
          { required: true, message: '请输入金额', trigger: 'blur' }
        ]
      },
      idDate: null,
      tableHeight: 0,
      isExceed: false,
      saleType: null,
      dialogChangeWarehouse: false,
      exchangeWarehouseId: null,
      goodsTagList:[],
      noEmptyTagList:[],
      lackBomShow:false,
      checkMaterialWareHouse:{id:0,name:''},
      dialogCheckMaterialWareHouse:false
    }
  },
  activated() {
    //获取上次进入Id
    const id = sessionStorage.getItem(this.$options.name + 'Id')
    //记录本次进入的Id
    sessionStorage.setItem(this.$options.name + 'Id', this.$route.params.id)
    if (!this.crud.header) this.getHeader()
    if (id !== this.$route.params.id) {
      if (this.$route.params.id === 'add') {
        // this.$set(this.crud, 'order', Object.assign({}, copyFrom))
        this.orderInit()
        this.crud.data = []
        // this.$set(this.crud,'data',[])
      } else if (this.$route.params.id.indexOf('copy') !== -1) {
        const copyid = this.$route.params.id.split('=')[1]
        this.crud.toGetCopyInfo(copyid)
      } else {
        this.crud.params.id = this.$route.params.id
        this.crud.refresh()
      }
    }

    this.idDate = this.$route.query.idDate
    if (this.idDate) {
      this.idList = JSON.parse(sessionStorage.getItem(this.idDate)) || []
    } else {
      this.idList = []
    }
    this.isExceed = this.$route.query.isExceed
  },
  // destroyed() {
  //   //销毁缓存   存在部分问题
  //   this.crud.cleanItemInfo(this.detailName)
  //   console.log(`${this.detailName}缓存清除成功`)
  // },
  // activated(){
  //   //获取缓存
  //   let detailName
  //
  //   if (/add$/.test(window.location.href)){
  //     detailName = 'salesOrder_add'
  //     this.isTheCache = false
  //     console.log(localStorage.getItem(detailName))
  //     if(localStorage.getItem(detailName) === null){
  //       this.orderInit()
  //       return
  //     }else {
  //       this.crud.data = []
  //       const _form = JSON.parse(localStorage.getItem('salesOrder_add'))
  //       if (_form.id === null) {
  //         this.crud.order = _form
  //         this.crud.data = _form.detailList
  //       } else {
  //         this.crud.cleanItemInfo('salesOrder_add')
  //         this.orderInit()
  //       }
  //       return
  //     }
  //   }else {
  //     // detailName = 'salesOrder'+window.location.href.match(/\/\S{3,5}$/)[0].split('/')[1]
  //     detailName = 'salesOrder'+window.location.href.split('/')[5]
  //
  //   }
  //   this.detailName = detailName
  //   this.crud.getItemInfo(detailName)
  // },
  // deactivated(){
  //   //切换时设置缓存
  //   if (
  //     !this.isTheCache
  //   ){
  //     const index = this.getTagsIndex()
  //     if (index !== -1){
  //     this.crud.order.detailList = this.crud.data
  //     localStorage.setItem(this.detailName, JSON.stringify(this.crud.order))
  //     console.log(`${this.detailName}缓存设置成功`)}
  //   }
  // },
  created() {
    this.basWarehouseList()
    this.setTableHeight()
    this.crud.headerInfo = {
      code: 'salesOrderDetail',
      userId: this.$store.state.user.user.userId,
      path: 'api/salesOrder/detail'
    }
    this.user = this.$store.state.user.user
    if (/add$/.test(window.location.href)) {
      this.getHeader()
      this.orderInit()
    }
    const href = location.href.split('/')
    if (href[5].includes('copyId')) {
      let strs = this.$route.params.id.split('=')
      this.crud.toGetCopyInfo(strs[1])
      this.crud.order.orderStatus = 'SAVE'
      this.getHeader()
    }
    this.getTagList()

  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.setTableHeight()
      })()
    }
    if (/add$/.test(window.location.href)) {
      // this.$refs.selectCustomer.$el.getElementsByTagName('input')[0].focus()
    } else {
      this.idDate = this.$route.query.idDate
      this.idList = JSON.parse(sessionStorage.getItem(this.idDate)) || []
      this.isExceed = this.$route.query.isExceed
    }
    this.$refs.table = this.$refs.tableParent.$children[0]
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table = this.$refs.tableParent.$children[0]
      this.$refs.table.doLayout()
    })
  },
  methods: {
    basWarehouseList(){
      basWarehouseList({page:1,size:999}).then(res=>{
        this.WarehouseList=res.content
        console.log('dddddddddddddddddddd',res);
      })
    },

    ChangeWarehouse() {
      this.dialogChangeWarehouse = false
      this.crud.saleToAccept(this.$route.params.id, this.form.exchangeWarehouseId)
    },
    bomStockCheck(){
      checkBomStock(this.crud.order.id).then(res=>{
        if (res.status === 200){
          this.$message.success('更新成功')
          this.crud.refresh()
        }
      })
    },
    getTagList(){
      getGoodsTagList({size:999}).then(res=>{
        this.goodsTagList = res.data.content
        this.noEmptyTagList = this.goodsTagList.filter(item=>!item.isZeroPrice).map(item=>item.id)
      })
    },
    toAccept(id) {
      if (this.crud.order.saleType === 5 && this.crud.order.type === 1) {
        this.dialogChangeWarehouse = true
        let a=this.WarehouseList.find(item=>item.name='临期库')
        console.log(a,'=========================================');
        this.form.exchangeWarehouseId=a.id
        this.form.exchangeWarehouseName=a.name
      } else {
        this.crud.saleToAccept(id)
      }
    },
    saleTypeChange(e) {
      this.saleType = e
      if (this.crud.order.saleType === 5 && this.crud.order.type === 1) {
        this.crud.data.forEach(item => {
          item.taxPrice = 0
          item.taxBoxPrice = 0
          item.taxAmount = 0
          item.billTaxPrice = 0
          item.billTaxBoxPrice = 0
          item.billTaxAmount = 0
        })
      }
      // console.log(data)
    },
    setTableHeight() {
      const ratio = this.getRatio() / 100
      this.tableHeight = (window.screen.height - (200 * ratio)) / ratio
    },
    setDeductionAmount(e){
      const num =Number(e)
      if (num < 0 || num > this.settlementData.customerDeductionAmount){
        this.settlementForm.deductionAmount = 0
      }
      this.deductionAmount()
    },
    deductionAmount(){
      this.settlementForm.curCancelAmount = (Number(this.settlementData.order.unCancelAmount) + Number(this.settlementForm.tailAmount || 0) - Number(this.settlementForm.deductionAmount || 0)).toFixed(6)
    },
    getRatio() {
      var ratio = 0
      var screen = window.screen
      var ua = navigator.userAgent.toLowerCase()

      if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio
      } else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
          ratio = screen.deviceXDPI / screen.logicalXDPI
        }

      } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth
      }

      if (ratio) {
        ratio = Math.round(ratio * 100)
      }
      return ratio
    },
    handleClose() {
      this.crud.props.searchToggle = !this.crud.props.searchToggle
    },
    getHeader() {
      const data = {
        modelName: 'salesOrderDetail',
        url: 'api/salesOrder/detail',
        userId: this.$store.state.user.user.userId
      }
      getHeaderProperties(data).then(res => {
        this.crud.header = JSON.parse(res.data.header.content)
        this.$forceUpdate()
      }).catch(err => {
        console.log(err)
      })
    },
    cancelCUDis() {
      this.isVolume = false
      this.goodsBrandDiscountList = null
      this.goodsDiscountList = null
      this.goodsTypeDiscountList = null
    },
    handleDisCl() {
      let criteria = {
        orderId: this.$route.params.id,
        type: this.activeName,
        goodsBrandDiscountList: this.goodsBrandDiscountList,
        goodsDiscountList: this.goodsDiscountList,
        goodsTypeDiscountList: this.goodsTypeDiscountList
      }
      batchDiscount(criteria).then(res => {
        // this.areaList = res
        this.crud.refresh()
        this.isVolume = false
        this.$message({
          message: '修改成功',
          type: 'success'
        })
      })
    },
    appendSave() {
      const data = {
        id: this.crud.order.id,
        detailList: this.crud.data
      }
      crudBasSaleSystem.append(data).then(res => {
        if (res.status === 200) {
          this.$message.success(res.msg)
          this.crud.refresh()
        } else {
          this.$message.error(res.msg)
        }
        this.crud.loadingClose()
      }).catch(e => this.crud.loadingClose())
    },
    handleClick(e) {
      let criteria = {
        orderId: this.$route.params.id,
        type: this.activeName
      }
      getBatchDiscountInfo(criteria).then(res => {
        this.goodsBrandDiscountList = res.data.goodsBrandDiscountList
        this.goodsDiscountList = res.data.goodsDiscountList
        this.goodsTypeDiscountList = res.data.goodsTypeDiscountList
        // this.areaList = res
      })
    },
    superReject() {
      crudBasSaleSystem.superReject(this.crud.order.id).then(res => {
        if (res.status === 200) {
          this.$message.success(res.msg)
          this.crud.refresh()
        } else {
          this.$message.error(res.msg)
        }

      })
    },
    volume() {
      // if(this.crud.selections[0].orderStatus != 'SAVE') {
      //   this.$message({
      //     message: '保存状态下才能操作',
      //     type: 'error'
      //   })
      //   return
      // }
      let criteria = {
        orderId: this.$route.params.id,
        type: this.activeName
      }
      this.isVolume = true
      getBatchDiscountInfo(criteria).then(res => {
        this.goodsBrandDiscountList = res.data.goodsBrandDiscountList
        this.goodsDiscountList = res.data.goodsDiscountList
        this.goodsTypeDiscountList = res.data.goodsTypeDiscountList
        // this.areaList = res
      })
    },
    closeDialog(val) {
      this.showQueryGoods = false
    },
    computedCount(row, type = 'split') {
      if (type === 'split') {
        if (row.splitGoodsCount > row.goodsCount || row.splitGoodsCount < 0) {
          this.$message.error('拆分数量不允许小于0或大于单据数量')
          this.$set(row, 'splitGoodsCount', 0)
          this.$set(row, 'splitMainNum', 0)
          this.$set(row, 'splitBoxNum', 0)
        }
      } else if (type === 'recycle') {
        if (row.acceptGoodsCount > row.acceptGoodsCount || row.acceptGoodsCount < 0) {
          this.$message.error('回收数量不允许小于0或大于验收数量')
          this.$set(row, 'recycleGoodsCount', 0)
          this.$set(row, 'recycleMainNum', 0)
          this.$set(row, 'recycleBoxNum', 0)
        }
      }
    },
    orderInit() {
      this.crud.order = {
        id: null,
        code: null,
        name: null,
        type: 1,
        saleType: 1,
        busDate: null,
        sourceType: null,
        sourceId: null,
        sourceCode: null,
        serialNumber: null,
        customerOrderCode: null,
        customerId: null,
        customerCode: null,
        customerName: null,
        isContact: 1,
        deptId: null,
        deptCode: null,
        deptName: null,
        userId: null,
        userCode: null,
        userName: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        count: null,
        boxCount: null,
        taxAmount: null,
        noTaxAmount: null,
        tax: null,
        discountAmount: null,
        acceptBoxCount: null,
        acceptTaxAmount: null,
        acceptNoTaxAmount: null,
        acceptTax: null,
        cancelAmount: null,
        unCancelAmount: null,
        receiveDate: null,
        carId: null,
        carCode: null,
        carName: null,
        loadId: null,
        loadCode: null,
        loadTime: null,
        driverUserId: null,
        driverUserCode: null,
        driverUserName: null,
        followUserId: null,
        followUserIds: null,
        followUserCode: null,
        followUserName: null,
        printStatus: null,
        printCount: null,
        customerAreaId: null,
        customerAreaCode: null,
        customerAreaName: null,
        customerTypeId: null,
        customerTypeCode: null,
        customerTypeName: null,
        pCustomerId: null,
        pCustomerCode: null,
        pCustomerName: null,
        mCustomerId: null,
        mCustomerCode: null,
        mCustomerName: null,
        scustomerId: null,
        scustomerCode: null,
        scustomerName: null,
        seq: null,
        orderStatus: null,
        acceptStatus: '0',
        cancelStatus: '0',
        remark: null,
        usableNum: null,
        orderRemark: null,
        createUserId: null,
        createUserCode: null,
        createUserName: null,
        createTime: null,
        updateUserId: null,
        updateUserCode: null,
        updateUserName: null,
        updateTime: null,
        closeUserId: null,
        closeUserCode: null,
        closeUserName: null,
        closeTime: null,
        deliveryAddress: null,
        checkStatus: 'SAVE',
        index: '0'
      }
      this.crud.data = []
      getDictDetail('t_sales_order_customer_is_follow_login_user_dept').then(res => {
        if (res.data.content[0].value === '1') {
          this.isDept = true
          if (this.user.deptId === 0) {
            this.$message.error('登录用户未配置部门，请先选择部门')
            return
          }
          this.crud.order.deptId = this.user.deptId
          this.customerParams['deptId'] = this.user.deptId
          this.crud.order.deptName = this.user.deptName
          if (!this.crud.order.customerId)
            this.$refs.selectCustomer.$el.getElementsByTagName('input')[0].focus()
        } else {
          this.$refs.selectCustomer.$el.getElementsByTagName('input')[0].focus()
        }
      })
    },
    getTime(date = new Date()) {
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      m = m < 10 ? ('0' + m) : m
      var d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      var h = date.getHours()
      h = h < 10 ? ('0' + h) : h
      var minute = date.getMinutes()
      minute = minute < 10 ? ('0' + minute) : minute
      var second = date.getSeconds()
      second = second < 10 ? ('0' + second) : second
      // +' '+h+':'+minute+':'+second;
      return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
    },
    right1() {
    },
    computedBill(row, type) {
      if (type === 'billTaxPrice') {
        row.billTaxBoxPrice = Number(row.billTaxPrice) * Number(row.boxUnitCount)
        row.billTaxAmount = Number(row.billTaxPrice) * Number(row.goodsCount)
      } else if (type === 'billTaxBoxPrice') {
        row.billTaxPrice = (Number(row.billTaxBoxPrice) / Number(row.boxUnitCount)).toFixed(2)
        row.billTaxAmount = Number(row.billTaxPrice) * Number(row.goodsCount)
      } else {
        row.billTaxPrice = (Number(row.billTaxAmount) / Number(row.goodsCount)).toFixed(2)
        row.billTaxBoxPrice = Number(row.billTaxPrice) * Number(row.boxUnitCount)
      }
    },
    deptChange(e) {
      if (this.isDept) this.customerParams['deptId'] = e.id
    },
    inputCount(row, type) {
      if (type === 'splitBoxNum' || type === 'splitMainNum') {
        const splitGoodsCount = Number(row.splitBoxNum ? row.splitBoxNum : 0) * Number(row.boxUnitCount) + Number(row.splitMainNum ? row.splitMainNum : 0)
        this.$set(row, 'splitGoodsCount', splitGoodsCount)
        this.computedCount(row)
      } else if (type === 'splitGoodsCount') {
        const boxCount = parseInt(Number(row.splitGoodsCount) / Number(row.boxUnitCount))
        const mainCount = Number(row.splitGoodsCount) % Number(row.boxUnitCount)
        this.$set(row, 'splitBoxNum', boxCount)
        this.$set(row, 'splitMainNum', mainCount)
        this.computedCount(row)
      } else if (type === 'recycleBoxNum' || type === 'recycleMainNum') {
        const recycleGoodsCount = Number(row.recycleBoxNum || 0) * Number(row.boxUnitCount) + Number(row.recycleMainNum || 0)
        this.$set(row, 'recycleGoodsCount', recycleGoodsCount)
        this.computedCount(row, 'recycle')
      } else if (type === 'recycleCount') {
        const boxCount = parseInt(Number(row.recycleGoodsCount) / Number(row.boxUnitCount))
        const mainCount = Number(row.recycleGoodsCount) % Number(row.boxUnitCount)
        this.$set(row, 'recycleBoxNum', boxCount)
        this.$set(row, 'recycleMainNum', mainCount)
        this.computedCount(row, 'recycle')
      }
    },
    selectRow(row, column, event) {
      if (row.isEmptyBoxAdd == '1') return
      this.$refs['table'].toggleRowSelection(row)
    },
    submitSplit() {
      const detailList = this.$refs.table.selection.filter(item => item.isEmptyBoxAdd !== '1')
      const data = {
        orderId: this.$route.params.id,
        detailList: detailList
      }
      split(data).then(res => {
        this.toSplitShow = false
        this.crud.refresh()
      })
    },
    getValue(e, i) {
      // this.crud.data[i].productName = e
      // let temp = this.crud.data[2]
      // this.crud.data[3] = temp
      this.crud.data.map(item => {
        // item.existId = 0
        // item.existNum = 0
        if (item.existBox === null) {
          item.existBox = 0
        }
        if (item.occupyBox === null) {
          item.occupyBox = 0
        }
      })
    },
    addInfo() {

    },
    billSplit() {

    },
    addDetail() {
      if (this.$route.params.id === 'add') {
        this.$message.error('当前已在添加界面')
        return
      }
      this.$router.replace({ path: '/redirect/sale/salesOrderDetail/add' })
    },
    queryEmptyBox() {
      // alert(window.location.href.match(/^\d+$/))
      emptyBox({ id: this.crud.order.id }).then(res => {
        this.emptyBoxList = res.data.content
        this.isEmptyBoxShow = true
      })
    },
    getInfo(e) {
      this.crud.order.customerCode = e.code
      this.crud.order.warehouseId = e.warehouseId
      this.crud.order.customerAreaName = e.customerAreaName
      this.crud.order.customerAreaId = e.customerAreaId
      this.crud.order.deptId = e.deptId
      this.crud.order.deptName = e.deptName
      this.crud.order.userId = e.userId
      this.crud.order.userName = e.userName
      this.crud.order.scustomerid = null
      this.sCustomerList = e.scustomerList
      this.crud.order.carId = e.carId
      this.crud.order.customerTypeId = e.customerTypeId
      this.crud.order.loadCode = e.loadCode
      this.crud.order.loadTime = e.loadTime
      this.crud.order.driverUserId = e.driverUserId
      this.crud.order.followUserId = e.followUserId
      this.crud.order.printStatus = e.printStatus
      this.crud.order.verifyCode = e.verifyCode
      this.crud.order.remark = e.remark
      this.crud.order.usableNum = e.usableNum
      this.crud.order.printCount = e.printCount
      this.crud.order.acceptStatus = e.acceptStatus
      this.crud.order.cancelStatus = e.cancelStatus
      this.crud.order.pickSeq = e.pickSeq
      this.crud.order.warehouseId = e.warehouseId
      this.crud.order.warehouseName = e.warehouseName
      this.crud.order.contactName = e.contactName
      this.crud.order.contactPhone = e.contactPhone
      this.crud.order.deliveryAddress = e.deliveryAddress
      this.crud.order.address = e.address
      try {
        if (e.scustomerList || e.scustomerList.lenght === 1) {
          this.crud.order.scustomerId = e.scustomerList[0].scustomerId
          this.crud.order.scustomerName = e.scustomerList[0].scustomerName
        } else {
          this.crud.order.scustomerId = null
          this.crud.order.scustomerName = null
          console.log('设置成功')
        }
      } catch (e) {
        this.crud.order.scustomerId = null
        this.crud.order.scustomerName = null
      }
      if (this.crud.data.length === 0) {
        this.crud.data.push({
          isSelected: true,
          id: null,
          code: null,
          name: null,
          type: null,
          saleType: 1,
          busDate: null,
          sourceType: null,
          sourceId: null,
          sourceCode: null,
          serialNumber: null,
          customerOrderCode: null,
          customerId: null,
          customerCode: null,
          customerName: null,
          isContact: 1,
          deptId: [],
          deptCode: null,
          deptName: null,
          userId: null,
          userCode: null,
          userName: null,
          warehouseId: null,
          warehouseCode: null,
          warehouseName: null,
          count: null,
          boxCount: null,
          taxAmount: null,
          noTaxAmount: null,
          tax: null,
          discountAmount: null,
          acceptBoxCount: null,
          acceptTaxAmount: null,
          acceptNoTaxAmount: null,
          acceptTax: null,
          cancelAmount: null,
          unCancelAmount: null,
          receiveDate: null,
          carId: null,
          carCode: null,
          carName: null,
          loadId: null,
          loadCode: null,
          loadTime: null,
          driverUserId: null,
          driverUserCode: null,
          driverUserName: null,
          followUserId: null,
          followUserIds: null,
          followUserCode: null,
          followUserName: null,
          printStatus: null,
          printCount: null,
          customerAreaId: null,
          customerAreaCode: null,
          customerAreaName: null,
          customerTypeId: null,
          customerTypeCode: null,
          customerTypeName: null,
          pCustomerId: null,
          pCustomerCode: null,
          pCustomerName: null,
          mCustomerId: null,
          mCustomerCode: null,
          mCustomerName: null,
          sCustomerId: null,
          sCustomerCode: null,
          sCustomerName: null,
          seq: null,
          orderStatus: null,
          acceptStatus: 0,
          cancelStatus: null,
          remark: null,
          orderRemark: null,
          createUserId: null,
          createUserCode: null,
          createUserName: null,
          createTime: null,
          updateUserId: null,
          updateUserCode: null,
          updateUserName: null,
          updateTime: null,
          closeUserId: null,
          closeUserCode: null,
          closeUserName: null,
          closeTime: null,
          billTaxPrice: null,
          billTaxBoxPrice: null,
          usableNum: null,
          billTaxAmount: null,
          locationId: null,
          locationName: null,
          goodsName: null
        })
        this.rowIndex = 0
        setTimeout(() => {
          this.$refs.table.setCurrentRow(this.crud.data[0])
          const list = this.$refs.table.$el.querySelectorAll('.el-table__body tr')[0].querySelectorAll('.el-input__inner,.el-textarea__inner')
          list[0].focus()
        }, 10)
      }
      // else {
      //   const  goodsIds = this.crud.data.filter(item=>!item.isPromotion).map(item=>item.goodsId).join(',')
      //   if (goodsIds.length){
      //     getGoods({goodsIds,customerId: this.crud.order.customerId}).then(res=>{
      //       console.log(res)
      //     })
      //   }
      // }


    },
    cancelCU() {
      this.form.id = null
      this.form.warehouseId = null
      this.isCopyToReturn = false
    },
    settlement(){
      settlementDraw({customerId: this.crud.order.customerId}).then(res=>{
        if (res.status === 200){
          this.settlementData.customerDeductionAmount = res.data.customerDeductionAmount
          this.settlementData.customerId = this.crud.order.customerId
          this.settlementData.order = this.crud.order
          this.settlementForm = {
            deductionAmount:0,
            receiptIds:'',
            curCancelAmount:0,
            tailAmount:0,
          },
            this.settlementShow = true
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    getById(id) {
      getSaleOrderDetail({ id: id }).then(res => {
        this.form = res.data.order
        this.detailList = res.data.content
      })


    },
    rightClick(row, column, event) {
      console.log('rightClick', row, column, event)
      this.testModeCode = row.testModeCode
      this.menuVisible = false // 先把模态框关死，目的是 第二次或者第n次右键鼠标的时候 它默认的是true
      this.menuVisible = true // 显示模态窗口，跳出自定义菜单栏
      event.preventDefault() //关闭浏览器右键默认事件
      this.CurrentRow = row
      var menu = document.querySelector('.menu')
      this.styleMenu(menu)
    },
    foo() {
      // 取消鼠标监听事件 菜单栏
      this.menuVisible = false
      document.removeEventListener('click', this.foo) // 关掉监听，
    },
    styleMenu(menu) {
      if (event.clientX > 1800) {
        menu.style.left = event.clientX - 100 + 'px'
      } else {
        menu.style.left = event.clientX + 1 + 'px'
      }
      document.addEventListener('click', this.foo) // 给整个document新增监听鼠标事件，点击任何位置执行foo方法
      if (event.clientY > 700) {
        menu.style.top = event.clientY - 30 + 'px'
      } else {
        menu.style.top = event.clientY - 10 + 'px'
      }
    },
    handleCopyToReturn() {
      this.isCopyToReturn = true
    },
    saveCancel() {
      this.$refs['cancelForm'].validate((valid) => {
        if (valid) {
          const that = this
          crudBasSaleSystem.superCancel({ ...this.cancel, id: this.crud.order.id }).then(res => {
            if (res.status === 200) {
              for (let key in that.cancel) {
                that.cancel[key] = null
              }
              that.$message.success(res.msg)
              that.crud.refresh()
              that.superCancelShow = false
            } else {
              that.$message.error(res.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    computeGoodsCount(row, index) {
      console.log(row)
      row.goodsCount = row.boxUnitCount * row.boxNum + row.mainUnitCount * row.mainNum
      this.computedMoney(row)
    },
    addGoodsRow() {
      if (this.crud.order.orderStatus === 'SAVE' || this.crud.order.orderStatus === null) {
        this.toAdd()
        this.rowIndex = this.crud.data.length - 1
        const p = new Promise(resolve => {
          setTimeout(() => {
            this.$refs.table.setCurrentRow(this.crud.data[this.rowIndex])
            resolve('22')
          }, 10)
        })
        p.then(res => {
          this.queryGoods = {
            index: this.crud.data.length - 1,
            ignoreGoodsTagNames: '回瓶回箱,瓶盖',
            goodsTagName: this.queryGoods.goodsTagName || ''
          }
          this.showQueryGoods = true
        })
        // this.queryGoods = { index: this.crud.data.length-1, ignoreGoodsTagNames: '回瓶回箱,瓶盖',goodsTagName: this.queryGoods.goodsTagName||''}
        // this.showQueryGoods = true
        return
      }
      this.$message.error('非保存单据不能添加')
    },
    findDuplicates(arr) {
      const duplicates = [];
      arr.forEach((item, index) => {
        const isDuplicate = arr.findIndex(
          (elem) =>
            elem.goodsId === item.goodsId && elem.goodsTagId === item.goodsTagId
        ) !== index;
        if (isDuplicate && !duplicates.includes(item)) {
          duplicates.push(item.goodsName);
        }
      });
      return duplicates;
    },

//判断商品是否重复
    checkGoods(){
      // const arr = this.crud.data.map(item=>item.goodsId)
      // const repeat = arr.filter((item, index) => arr.indexOf(item) !== index)
      // let repeatGoodsList = repeat.map(item=>{
      //   return this.crud.data.find(val=>val.goodsId === item && val.goodsTagId === ).goodsName
      // })

      const repeatGoodsList = this.findDuplicates(this.crud.data)
      let repeatStr = ''
      if(repeatGoodsList.length)
      repeatStr = `商品${repeatGoodsList.join(',')}重复`
      let emptyStr = ''
        this.crud.data.forEach((item,index)=>{
        if(!item.taxPrice && this.noEmptyTagList.includes(item.goodsTagId))emptyStr += `第${index+1}行${item.goodsName}价格为0 ; `
      })
      return repeatStr+' '+emptyStr
    },


    couputedGoodsUnitCount(row) {
      //判断是否满足最小销售单位和退货单位
      if (row.boxUnitCount > 0) {
        row.boxNum = parseInt(row.goodsCount / row.boxUnitCount)
      }
      if (row.mainUnitCount > 0) {
        row.mainNum = parseInt((row.goodsCount - row.boxUnitCount * row.boxNum) / row.mainUnitCount)
      }
      // if (row.minSaleUnitCount && this.form.type == 1 && row.minSaleUnitCount > 0) {
      //   if (row.goodsCount % row.mainUnitCount != 0) {
      //     //不满足
      //     this.$message.error('请输入最小销售单位' + row.minSaleUnitCount + '整数倍的数量')
      //     return false
      //   }
      // }
      // if (row.minReturnUnitCount && this.form.type == 2 && row.minReturnUnitCount > 0) {
      //   if (row.goodsCount % row.mainUnitCount != 0) {
      //     //不满足
      //     this.$message.error('请输入最小退货单位' + row.minReturnUnitCount + '整数倍的数量')
      //     return false
      //   }
      // }
      this.computedMoney(row)
    },
    changeGoods(val) {
      this.showQueryGoods = false
      this.crud.diaLogGoodsChange(val)

      if (this.emptyList.includes(this.crud.order.saleType) && this.crud.order.type === 1) {
        val.row.taxPrice = 0
        val.row.taxBoxPrice = 0
        val.row.taxAmount = 0
        val.row.billTaxPrice = 0
        val.row.billTaxBoxPrice = 0
        val.row.billTaxAmount = 0
      }
      setTimeout(() => {
        this.$refs.table.setCurrentRow(this.crud.data[this.rowIndex])
      }, 10)
    },
    computedMoney(row) {
      //计算价格
      row.noTaxAmount = this.formatNum(row.noTaxBoxPrice * row.boxNum + row.noTaxPrice * row.mainNum)
      row.taxAmount = this.formatNum(row.taxBoxPrice * row.boxNum + row.taxPrice * row.mainNum)

      row.billTaxAmount = Number(row.billTaxPrice) * Number(row.goodsCount)
      // this.calcuForm() //计算form参数
      this.$forceUpdate()
    },
    toAddList() {
      // console.log(this.crud.order.saleType)
      // console.log(this.crud.order.detailList)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          //校验通过
          this.showAddBatchDialog = true
        } else {
          if (!this.crud.order.customerId) {
            this.$message.error('请先选择客户')
          }
          if (!this.crud.order.type) {
            this.$message.error('请先选择单据类型')
          }
          // if (!this.crud.order.buyChannel) {
          //   this.$message.error("请先选择采购渠道")
          // }
        }
      })
    },
    toActivityGoods() {
      this.toActivityShow = true
    },
    setZeroPrice(){
      for(let i of this.crud.selections){
        i.taxPrice = 0
        i.noTaxPrice = 0
        i.taxAmount = 0
        i.noTaxAmount = 0
        i.taxBoxPrice = 0
        i.noTaxBoxPrice = 0
        i.billTaxPrice = 0
        i.billTaxAmount = 0
        i.billTaxBoxPrice = 0
      }
    },
    resetDetailPrintStatus(){
      const data ={
        orderId:this.crud.order.id,
        detailIds:this.crud.selections.map(item=>item.id).join(",")
      }
      resetDetailPrint(data).then(res=>{
        if(res.status === 200){
          this.$message.success('重置成功')
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    // 新增
    toAdd() {

      if (!this.crud.order.customerId) {
        this.$message({
          message: '请先选择客户',
          type: 'error'
        })
        return
      }
      if (!this.crud.order.type) {
        this.$message({
          message: '请先选择单据类型',
          type: 'error'
        })
        return
      }
      if (this.crud.order.isAccept === 1) {
        this.$message({
          message: '已验收不允许新增',
          type: 'error'
        })
        return
      }
      // if(!this.crud.order.buyChannel){
      //   this.$message({
      //     message: '请先选择采购渠道',
      //     type: 'error'
      //   })
      //   return
      // }
      this.crud.data.push({
        isSelected: true,
        id: null,
        code: null,
        name: null,
        type: null,
        saleType: 1,
        busDate: null,
        sourceType: null,
        sourceId: null,
        sourceCode: null,
        serialNumber: null,
        customerOrderCode: null,
        customerId: null,
        customerCode: null,
        customerName: null,
        isContact: 1,
        deptId: [],
        deptCode: null,
        deptName: null,
        userId: null,
        userCode: null,
        userName: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        count: null,
        boxCount: null,
        taxAmount: null,
        noTaxAmount: null,
        tax: null,
        discountAmount: null,
        acceptBoxCount: null,
        acceptTaxAmount: null,
        acceptNoTaxAmount: null,
        acceptTax: null,
        cancelAmount: null,
        unCancelAmount: null,
        receiveDate: null,
        carId: null,
        carCode: null,
        carName: null,
        loadId: null,
        loadCode: null,
        loadTime: null,
        driverUserId: null,
        driverUserCode: null,
        driverUserName: null,
        followUserId: null,
        followUserIds: null,
        followUserCode: null,
        followUserName: null,
        printStatus: null,
        printCount: null,
        customerAreaId: null,
        customerAreaCode: null,
        customerAreaName: null,
        customerTypeId: null,
        customerTypeCode: null,
        customerTypeName: null,
        pCustomerId: null,
        pCustomerCode: null,
        pCustomerName: null,
        mCustomerId: null,
        mCustomerCode: null,
        mCustomerName: null,
        sCustomerId: null,
        sCustomerCode: null,
        sCustomerName: null,
        seq: null,
        orderStatus: null,
        acceptStatus: 0,
        cancelStatus: null,
        remark: null,
        usableNum: null,
        orderRemark: null,
        createUserId: null,
        createUserCode: null,
        createUserName: null,
        createTime: null,
        updateUserId: null,
        updateUserCode: null,
        updateUserName: null,
        updateTime: null,
        closeUserId: null,
        closeUserCode: null,
        closeUserName: null,
        closeTime: null,
        billTaxPrice: null,
        billTaxBoxPrice: null,
        billTaxAmount: null,
        locationId: null,
        locationName: null,
        goodsName: null
      })
    },
    getDetail(id) {
    },
    selectionChangeHandler(selection) {
      console.log(selection)
    },
    getArrDifference(arr1, arr2) {
      const list = Array.from(new Set([...arr1, ...arr2]))
      return {
        arr1: list.filter(item => arr1.indexOf(item) === -1),
        arr2: list.filter(item => arr2.indexOf(item) === -1)
      }
    },
    addGoods(val) {
      const data = val.filter(item => item.goodsCount > 0)
      data.forEach(item => {
        const goods = this.crud.data.find(val => val.giftId === item.giftId)
        if (goods) {
          goods.goodsCount = Number(goods.goodsCount) + Number(item.goodsCount)
          goods.mainNum = Number(goods.mainNum) + Number(item.mainNum)
          goods.boxNum = Number(goods.boxNum) + Number(item.boxNum)
          goods.taxAmount = 0
        } else {
          this.crud.data.push(item)
        }
      })
      // const dataGiftList = this.crud.data.filter(item=>item.giftId).map(item=>item.giftId)
      // const updateGiftList = val.map(item=>item.giftId)
      // //差异数组
      // const {arr1,arr2} =this.getArrDifference(dataGiftList,updateGiftList)
      // val.forEach(item => {
      //   const index = arr1.indexOf(item.giftId)
      //   if (index !== -1){
      //     this.crud.data.push(item)
      //   }else {
      //     const goods = this.crud.data.find(val=>val.giftId === item.giftId)
      //     goods.boxCount = item.boxCount
      //     goods.boxNum = item.boxNum
      //     goods.mainNum = item.mainNum
      //     goods.goodsCount = item.goodsCount
      //   }
      // this.crud.data.push(item)
      // })
      // arr2.forEach(item=>{
      //   const index = this.crud.data.findIndex(val=>val.giftId === item)
      //   this.crud.data.splice(index,1)
      // })
      this.toActivityShow = false
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    toEdit(row) {
      let id = 0
      if (row) {
        id = row.id
      }
      this.$router.push({
        path: 'salesOrderDetail/' + id,
        query: { id: id }
      })
    },
    setDetailWarehouse(e) {
      if (!this.crud.order.warehouseId) {
        return
      }
      for (let i of this.crud.data) {
        i.warehouseId = e.id
        i.warehouseName = e.name
      }

    },
    // 保存
    submit() {
      if (!this.crud.order.warehouseId) {
        this.$message.error('请检查仓库')
        return false
      }
      const ids = []
      this.crud.data.forEach((item, index) => {
        if (!item.goodsId) {
          ids.push(index)
        }
      })
      for (let i = ids.length - 1; i >= 0; i--) {
        this.crud.data.splice(ids[i], 1)
      }
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }

        const table_rules = [
          // {name: '商品名称', value: 'goodsName'},
          { name: '仓库', value: 'goodsCount' }
        ]
        const result = table_rules.some(({ name, value }) => {
          // const rules = this.$refs.table.data.some((item, index) => {
          //   if (!this.tableRules((index + 1), name, item[value])) return true
          // })
          const rules = this.$refs.table.data.every(item => item.goodsCount === null || item.goodsCount === undefined)
          // this.$message.error('请检查数量不能为空')
          if (rules) return true
        })
        if (!result){
          const str = this.checkGoods()
          if (str.trim(str)){
            this.$confirm(str, '提示', {
              confirmButtonText: '保存',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(()=>{
              this.save()
            })
          }else {
            this.save()
          }
        }
      })
    },
    async submitAnd() {
      if (this.crud.data.some(item => !item.goodsCount && item.isEmptyBoxAdd != '1')) {
        this.$message.error('存在数量为0的商品')
        return false
      }
      if (!this.crud.order.warehouseId) {
        this.$message.error('请检查仓库')
        return false
      }
      if (this.crud.order.type === 2 && !this.crud.order.driverUserIds) {
        this.$message.error('退货单司机不能为空')
        return
      }
      if (this.crud.order.type === 1) {
        this.crud.loadingOpen()
        const res = await checkCustomerIsExceed({ customerId: this.crud.order.customerId })
        if (res.result === 1) {
          this.crud.loadingClose()
          this.$message.error(res.message)
          return
        }
      }
      const ids = []
      this.crud.data.forEach((item, index) => {
        if (!item.goodsId) {
          ids.push(index)
        }
      })
      for (let i = ids.length - 1; i >= 0; i--) {
        this.crud.data.splice(ids[i], 1)
      }
      this.$refs['form'].validate(valid => {
        if (!valid) {
          this.crud.loadingClose()
          return
        }
        const table_rules = [
          // {name: '商品名称', value: 'goodsName'},
          { name: '数量', value: 'goodsCount' }
        ]
        const result = table_rules.some(({ name, value }) => {
          // const rules = this.$refs.table.data.some((item, index) => {
          //   if (!this.tableRules((index + 1), name, item[value])) return true
          // })
          const rules = this.$refs.table.data.every(item => item.goodsCount === null || item.goodsCount === undefined)
          if (rules) {
            this.crud.loadingClose()
            return true
          }
        })
        if (!result) this.saveBTM(1)
      })
    },

    async toSuperPass(id) {
      if (this.crud.data.some(item => !item.goodsCount && item.isEmptyBoxAdd != '1')) {
        this.$message.error('存在数量为0的商品')
        return false
      }
      if (!this.crud.order.warehouseId) {
        this.$message.error('请检查仓库')
        return false
      }
      this.crud.loadingOpen()
      if (this.crud.order.type === 1) {
        const res = await checkCustomerIsExceed({ customerId: this.crud.order.customerId })
        this.crud.loadingClose()
        if (res.result === 1) {
          this.$message.error(res.message)
          if (res.result === 1) {
            if (this.$route.params.id !== 'add') {
              this.$confirm('该客户已超账期是否确认审核', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.crud.loadingOpen()
                this.crud.loading = true
                this.crud.toSuperPass(id)
              }).catch(() => {

              })
            }
            return
          }
        }
      }

      this.crud.toSuperPass(id)
    },

    tableRules(index, name, value) {
      if (!value) {
        Notification.error({ title: '序号【' + index + '】' + name + '不能为空' })

        return false
      } else return true
    },
    showToRecycle() {
      // this.recycleData = [...this.crud.data.filter(item=>item.isEmptyBoxAdd != '1' && !item.recycleGoodsCount )]
      // this.recycleData.forEach(e=>{
      //   this.$set(e,'recycleGoodsCount',0)
      //   this.$set(e,'recycleMainNum',0)
      //   this.$set(e,'recycleBoxNum',0)})

      crudBasSaleSystem.recycleDetailList({ id: this.crud.order.id }).then(res => {
        this.recycleData = res.data.detailList
      })
      this.toRecycleShow = true
    },
    saveBTM(num) {
      let that = this
      this.crud.order.detailList = this.crud.data
      let params = this.crud.order
      const href = location.href.split('/')
      if (href[5].includes('copyId')) {
        this.crud.order.id = null
      }
      if (this.crud.order.orderStatus !== 'SAVE') {
        params.isEditWithoutReject = 1
      }

      crudSalesOrder.saveAndPass(params).then(res => {
        if (res.success) {
          this.crud.order = res.data
          // this.crud.data = res.data.detailList
          let id = res.data.id
          if (this.$route.params.id == 'add' || href[5].includes('copyId')) {
            // this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.replace('/redirect/sale/salesOrderDetail/' + id)
            // this.crud.cleanItemInfo('salesOrder_add')
          }
          this.$message({
            message: '保存并审核成功',
            type: 'success'
          })
          this.isTheCache = true
          that.crud.refresh()
          that.crud.loadingClose()
        } else {
          that.crud.loadingClose()
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }

      }).catch((res) => {
        that.crud.loadingClose()
      })
    },
    //检查bom库存减少
    showLackBom(){
      this.dialogCheckMaterialWareHouse = false
      this.lackBomShow = true
    },

    //保存
    save(num) {
      let that = this
      console.log(this.crud.order.type)
      if (this.crud.order.type === 2 && !this.crud.order.driverUserIds) {
        this.$message.error('退货单司机不能为空')
        return
      }
      that.crud.loadingOpen()
      for (let i of this.crud.data) {
        if (!i.warehouseId) {
          i.warehouseId = this.crud.order.warehouseId
        }
      }
      const isAppend = this.crud.data.every(item => item.id)
      //追加保存
      if ((this.crud.order.orderStatus === 'PASS' || this.crud.order.orderStatus === 'CLOSE') && !isAppend) {
        this.appendSave()
        return
      }
      this.crud.order.detailList = this.crud.data
      let params = this.crud.order
      const href = location.href.split('/')
      if (href[5].includes('copyId')) {
        this.crud.order.id = null
      }
      if (this.crud.order.orderStatus !== 'SAVE') {
        params.isEditWithoutReject = 1
      }
      params.sCustomerId = params.scustomerId
      crudBasSaleSystem.add(params).then(res => {
        if (res.success) {
          this.crud.order = res.data
          // this.crud.data = res.data.detailList
          let id = res.data.id
          if (this.$route.params.id == 'add' || href[5].includes('copyId')) {
            // this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.replace('/redirect/sale/salesOrderDetail/' + id)
            // this.crud.cleanItemInfo('salesOrder_add')
          }
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.isTheCache = true
          that.crud.refresh()
          that.crud.loadingClose()
        } else {
          that.crud.loadingClose()
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }

      }).catch((res) => {
        that.crud.loadingClose()
      })
    },
    cancel(id) {
      this.$store.dispatch('tagsView/delView', {
        path: '/sale/salesOrderDetail/' + id || this.id
      }).then(({ visitedViews }) => {
        const latestView = visitedViews.slice(-1)[0]
        if (latestView) {
          this.$router.push(latestView)
        } else {
          // now the default is to redirect to the home page if there is no tags-view,
          // you can adjust it according to your needs.
          if (view.name === 'Dashboard') {
            // to reload home page
            this.$router.replace({ path: '/redirect' + view.fullPath })
          } else {
            this.$router.push('/')
          }
        }
      })
    },
    async pass(type, id) {
      if (this.crud.data.some(item => !item.goodsCount && item.isEmptyBoxAdd != '1')) {
        this.$message.error('存在数量为0的商品')
        return false
      } else if (!this.crud.order.warehouseId) {
        this.$message.error('请检查仓库')
        return false
      } else if (this.crud.order.type === 2 && !this.crud.order.driverUserIds) {
        this.$message.error('退货单司机不能为空')
        return
      }
      if (this.crud.order.type === 1) {
        this.crud.loadingOpen()
        const res = await checkCustomerIsExceed({ customerId: this.crud.order.customerId })
        this.crud.loadingClose()
        if (res.result === 1) {
          this.$message.error(res.message)
          return
        }
      }
      this.crud.doDetailPassOrReject(type, id)
    },
    async noPass(id) {
      if (this.crud.order.type === 1) {
        const res = await checkCustomerIsExceed({ customerId: this.crud.order.customerId })
        if (res.result === 1) {
          this.$message.error(res.message)
          return
        }
      }
      this.crud.noPass(id)
    },
    afterChangeGoods(goods) {
      this.showAddBatchDialog = false
      //去重，已经去重
      let arr = this.detailList.map(detail => detail.goodsId)
      goods.forEach(good => {
        good.isSelected = true
        goods.warehouseId = 0
        goods.locationId = 0
        goods.storehouseId= 0
        this.crud.data.push(good)
      })
      // this.calcuForm()
    },
    // calcuForm() {
    //   //统计总金额和单独数量
    //   let count = 0, boxCount = 0, taxAmount = 0, noTaxAmount = 0
    //   this.crud.data.forEach(good => {
    //     count += parseInt(good.mainNum)
    //     boxCount += parseInt(good.boxNum)
    //     taxAmount += parseFloat(good.taxAmount)
    //     noTaxAmount += parseFloat(good.noTaxAmount)
    //   })
    //   this.form.count = count
    //   this.form.boxCount = boxCount
    //   this.form.taxAmount = taxAmount
    //   this.form.noTaxAmount = noTaxAmount
    // },
    toDelete(scope) {
      let index = scope.$index
      this.crud.data.splice(index, 1)
    },
    delAddRowPlus(row) {
      let indx = row.seq

      if (this.$route.params.id !== 'add') {
        this.$confirm('此操作将直接删除此条产品记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.delRow(indx)
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        })
      } else {
        this.crud.data.splice(index, 1)
      }
    },
    //切换行索引
    switchRowIndex(row) {
      if (row.index === this.rowIndex) {
        this.rowIndex = -1
        return
      }
      this.rowIndex = row.index
    },
    delAddRow(indx) {
      const selectCount = this.$refs.table.selection.length
      this.$confirm(`此操作将直接删除${selectCount || 0}条产品记录, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.crud.order.orderStatus === 'PASS' || this.crud.order.orderStatus === 'CLOSE') {
          const delList = this.$refs.table.selection.filter(item => !item.id)
          let delObj
          while (delObj = delList.pop()) {
            const index = this.crud.data.findIndex(item => item === delObj)
            if (~index) {
              this.crud.data.splice(index, 1)
            }
          }
        } else {
          const ids = []
          const promotionGroupKeyList = new Set()
          const ifEmptyBox = this.$refs.table.selection.filter(item => item.isEmptyBoxAdd == '1').map(item => item.goodsId)
          for (let i of this.$refs.table.selection) {
            if (ifEmptyBox.includes(i.goodsId)) {
              continue
            }
            if (i.promotionGroupKey) {
              i.isGift !== '1' && promotionGroupKeyList.add(i.promotionGroupKey)
              if (i.promotionEmptyBoxKey) {
                try {
                  const emptyBox = this.crud.data.find(item => (item.promotionEmptyBoxKey === i.promotionEmptyBoxKey) && item.isEmptyBoxAdd == '1')
                  const index = this.crud.data.indexOf(emptyBox)
                  emptyBox.id && ids.push(emptyBox.id)
                  i.id && ids.push(i.id)
                  this.crud.data.splice(index, 1)
                } catch (e) {
                  console.log(e)
                }
              }
            }
            const index = this.crud.data.indexOf(i)
            i.id && ids.push(i.id)
            this.crud.data.splice(index, 1)
          }
          //促销删除的处理
          if (promotionGroupKeyList.size) {
            const promotionGoodsList = this.crud.data.filter(item => promotionGroupKeyList.has(item.promotionGroupKey))
            for (let i in promotionGoodsList) {
              promotionGoodsList[i].id && ids.push(promotionGoodsList[i].id)
              this.crud.data.splice(this.crud.data.indexOf(promotionGoodsList[i]), 1)
            }
          }
          //删除对应空箱
          ifEmptyBox.forEach(item => {
            this.crud.data.splice(this.crud.data.indexOf(item, 1))
          })
          ids && this.delRows(Array.from(new Set(ids)))
        }

        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // });
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      })
    },
    delRows(ids) {
      batchRemoveDetail(ids).then(res => {
      })
    },
    saveSettlement(){
      if (this.settlementForm.receiptIds){
        this.settlementForm.id = this.settlementData.order.id
        settlementSave(this.settlementForm)
        this.settlementShow = false
      }else {
        this.$message.error('请先选择收款单')
      }
    },
    unCancel() {
      const that = this
      crudBasSaleSystem.superUnCancel({ id: this.crud.order.id }).then(res => {
        if (res.status === 200) {
          that.$message.success(res.msg)
          that.crud.refresh()
        } else {
          that.$message.error(res.msg)
        }
      })
    },
    removeGiftGoods(index) {
      if (this.crud.data[index].giftId) {
        const gift = this.giftIds.indexOf(this.crud.data[index].giftId)
        this.giftIds.splice(gift, 1)
      }
    },
    showHistory(row) {
      this.showHistoryDialog = true
      this.current = row
    },
    showPriceDetail() {
      this.showPriceDialog = true
    },
    getGiftCount(promotionGoods, giftGoods, ruleList) {

      // 判断活动商品满赠类型
      if (ruleList[0].reachType === 2) {
        // 阶梯过滤出当前促销符合的条件
        const satisfyList = ruleList.filter(item => item.full <= promotionGoods.goodsCount)
        // 查询最大符合条件
        let satisfy = satisfyList.slice(-1)[0]
        // 符合促销
        if (satisfy) {
          // 计算最大满足倍数
          const promotionNum = parseInt(Number(promotionGoods.goodsCount) / satisfy.full)
          // 计算最大赠送赠品数量
          const giftNum = promotionNum * satisfy.result
          // 判断当前赠品数量是否超最大可赠送数量
          return `${giftNum}${satisfy.resultType === 2 ? '瓶' : '箱'}`
        } else {
          return '0瓶'
        }
      } else if (ruleList[0].reachType === 3) {
        // 阶梯过滤出当前促销符合的条件
        const satisfyList = ruleList.filter(item => item.full <= promotionGoods.boxNum)
        // 查询最大符合条件
        let satisfy = satisfyList.slice(-1)[0]
        // 符合促销
        if (satisfy) {
          // 计算最大满足倍数
          const promotionNum = parseInt(Number(promotionGoods.boxNum) / satisfy.full)
          // 计算最大赠送赠品数量
          const giftNum = promotionNum * satisfy.result
          // 判断当前赠品数量是否超最大可赠送数量
          // 判断赠品类型
          return `${giftNum}${satisfy.resultType === 2 ? '瓶' : '箱'}`
        } else {
          return '0瓶'
        }
      }
    },
    changGoodsCount(row) {
      if (row.isOne === 1) {
        const promotionData = JSON.parse(row.promotionData)
        const gift = promotionData.gift
        const ruleList = promotionData.ruleList
        const giftCount = this.getGiftCount(row, gift, ruleList)
        const num = Number(giftCount.match(/\d+/)[0])
        const unitName = giftCount.match(/\D+/)[0]
        if (num === 0) {
          const dataList = this.crud.data.filter(item => item.promotionGroupKey == row.promotionGroupKey && item !== row)
          const delList = []
          dataList.forEach(item => {
            const index = this.crud.data.findIndex(val => val === item)
            const id = this.crud.data[index].id
            id && delList.push(id)
            this.crud.data.splice(index, 1)
          })
          this.$message.error('删除赠品后请及时保存')
          this.delRows(delList)
        } else {
          const giftData = this.crud.data.find(item => item.promotionGroupKey == row.promotionGroupKey && item.isGift == '1')
          if (giftData) {
            if (unitName === '箱') {
              giftData.boxNum = num
              giftData.goodsCount = giftData.boxNum * Number(giftData.boxUnitCount)
            } else {
              giftData.goodsCount = num
              giftData.boxNum = parseInt(giftData.goodsCount / Number(giftData.boxUnitCount))
              giftData.mainNum = giftData.goodsCount % Number(giftData.boxUnitCount)
            }
            const emptyBox = this.crud.data.find(item => item.promotionEmptyBoxKey == gift.promotionEmptyBoxKey && item.isEmptyBoxAdd == '1')
            if (emptyBox) {
              emptyBox.boxNum = Number(giftData.boxNum)
              emptyBox.mainNum = 0
              emptyBox.goodsCount = emptyBox.boxNum
              emptyBox.billTaxPrice = emptyBox.billTaxPrice || emptyBox.taxPrice
              emptyBox.billTaxBoxPrice = emptyBox.billTaxBoxPrice || emptyBox.taxBoxPrice
              emptyBox.taxAmount = emptyBox.goodsCount * emptyBox.taxPrice
              emptyBox.billTaxAmount = emptyBox.billTaxPrice * emptyBox.goodsCount
              emptyBox.boxCount = emptyBox.boxNum
            } else {
              const emptyBox = promotionData.emptyBox
              emptyBox.boxNum = Number(giftData.boxNum)
              emptyBox.mainNum = 0
              emptyBox.goodsCount = emptyBox.boxNum
              emptyBox.billTaxPrice = emptyBox.billTaxPrice || emptyBox.taxPrice
              emptyBox.billTaxBoxPrice = emptyBox.billTaxBoxPrice || emptyBox.taxBoxPrice
              emptyBox.taxAmount = emptyBox.goodsCount * emptyBox.taxPrice
              emptyBox.billTaxAmount = emptyBox.billTaxPrice * emptyBox.goodsCount
              emptyBox.boxCount = emptyBox.boxNum
              const index = this.crud.data.findIndex(item => item == gift)
              this.crud.data.splice(index + 1, 0, emptyBox)
            }
          } else {
            const giftData = Object.assign({}, gift)
            if (unitName === '箱') {
              giftData.boxNum = num
              giftData.goodsCount = giftData.boxNum * Number(giftData.boxUnitCount)
            } else {
              giftData.goodsCount = num
              giftData.boxNum = parseInt(giftData.goodsCount / Number(giftData.boxUnitCount))
              giftData.mainNum = giftData.goodsCount % Number(giftData.boxUnitCount)
            }
            const index = this.crud.data.findIndex(item => item === row)
            this.crud.data.splice(index + 1, 0, giftData)
            const emptyBox = this.crud.data.find(item => item.promotionEmptyBoxKey == row.promotionEmptyBoxKey && item.isEmptyBoxAdd == '1')
            if (emptyBox) {
              emptyBox.boxNum = Number(giftData.boxNum)
              emptyBox.mainNum = 0
              emptyBox.goodsCount = emptyBox.boxNum
              emptyBox.billTaxPrice = emptyBox.billTaxPrice || emptyBox.taxPrice
              emptyBox.billTaxBoxPrice = emptyBox.billTaxBoxPrice || emptyBox.taxBoxPrice
              emptyBox.taxAmount = emptyBox.goodsCount * emptyBox.taxPrice
              emptyBox.billTaxAmount = emptyBox.billTaxPrice * emptyBox.goodsCount
              emptyBox.boxCount = emptyBox.boxNum
            } else {
              const emptyBox = promotionData.emptyBox
              emptyBox.boxNum = Number(giftData.boxNum)
              emptyBox.mainNum = 0
              emptyBox.goodsCount = emptyBox.boxNum
              emptyBox.billTaxPrice = emptyBox.billTaxPrice || emptyBox.taxPrice
              emptyBox.billTaxBoxPrice = emptyBox.billTaxBoxPrice || emptyBox.taxBoxPrice
              emptyBox.taxAmount = emptyBox.goodsCount * emptyBox.taxPrice
              emptyBox.billTaxAmount = emptyBox.billTaxPrice * emptyBox.goodsCount
              emptyBox.boxCount = emptyBox.boxNum
              const index = this.crud.data.findIndex(item => item === giftData)
              this.crud.data.splice(index + 1, 0, emptyBox)
            }
          }
        }
      }
      if (row.giftId && row.goodsCount > row.unGiftGoodsCount) {
        this.$message({
          message: '下单数量不可大于可下单数量',
          type: 'error'
        })
        row.boxNum = 0
        row.mainNum = 0
        row.goodsCount = 0
      }
    },
    sum(type) {
      const emptyBoxAdd = ['goodsCount', 'boxNum', 'mainNum', 'boxCount']
      let sum = 0
      for (let i in this.crud.data) {
        if (this.crud.data[i].isEmptyBoxAdd == 1 && emptyBoxAdd.includes(type)) {
          continue
        }
        sum += Number(this.crud.data[i][type])
      }
      return sum
    },
    selectSum(type) {
      let sum = 0
      const emptyBoxAdd = ['goodsCount', 'boxNum', 'mainNum']
      for (let i in this.crud.selections) {
        if (this.crud.selections[i].isEmptyBoxAdd == 1 && emptyBoxAdd.includes(type)) {
          continue
        }
        sum += Number(this.crud.selections[i][type])
      }
      return sum
    },
    /**
     * 合计行
     */
    sumAuxiliaryCount(boxNum, mainNum) {
      let sum = ''
      let boxNumSum = 0
      let mainNumsum = 0
      for (let i in this.crud.data) {
        if (this.crud.data[i].isEmptyBoxAdd == 1) {
          continue
        }
        boxNumSum += Number(this.crud.data[i][boxNum])
        mainNumsum += Number(this.crud.data[i][mainNum])
      }
      return `${boxNumSum.toFixed(2)}箱${mainNumsum.toFixed(2)}瓶`
    },
    sumSelectAuxiliaryCount(boxNum, mainNum) {
      let sum = ''
      let boxNumSum = 0
      let mainNumsum = 0
      console.log(this.$refs.table)
      for (let i in this.$refs.table.selection) {
        console.log(this.$refs.table.selection[i].isEmptyBoxAdd)
        if (this.$refs.table.selection[i].isEmptyBoxAdd == 1) {
          continue
        }
        boxNumSum += Number(this.$refs.table.selection[i][boxNum])
        mainNumsum += Number(this.$refs.table.selection[i][mainNum])
      }
      return `${boxNumSum}箱${mainNumsum}瓶`
    },
    summaryMethod({ columns, data }) {
      const sums = []
      const selectSumList = []
      sums.push('合计')
      selectSumList.push('选中')
      const summaryList = ['boxCount', 'taxAmount', 'productCount', 'totalGrossWeight', 'totalNetWeight', 'count', 'noTaxAmount',
        'discountAmount', 'acceptBoxCount', 'acceptGoodsCount', 'acceptTaxAmount', 'acceptTax', 'cancelAmount', 'unCancelAmount', 'goodsCount',
        'checkGoodsCount', 'inAmount', 'balanceAmount', 'tax', 'acceptBoxNum', 'acceptMainNum', 'acceptNoTaxAmount', 'enterGoodsCount',
        'enterBoxCount', 'enterBoxNum', 'enterMainNum', 'enterTaxAmount', 'enterNoTaxAmount', 'enterTax', 'returnGoodsCount', 'returnBoxCount',
        'returnBoxNum', 'returnMainNum', 'returnTaxAmount', 'returnNoTaxAmount', 'returnTax', 'sendGoodsCount', 'sendBoxCount', 'sendBoxNum',
        'sendMainNum', 'sendTaxAmount', 'sendNoTaxAmount', 'sendTax', 'returnBottleBoxGoodsCount', 'returnBottleBoxBoxCount', 'returnBottleBoxBoxNum',
        'returnBottleBoxMainNum', 'returnBottleBoxTaxAmount', 'returnBottleBoxNoTaxAmount', 'returnBottleBoxTax', 'buyGoodsCount', 'buyBoxCount',
        'buyBoxNum', 'buyMainNum', 'buyTaxAmount', 'buyNoTaxAmount', 'buyTax', 'saleGoodsCount', 'saleBoxCount', 'saleBoxNum', 'saleMainNum',
        'saleTaxAmount', 'saleNoTaxAmount', 'saleTax', 'allotGoodsCount', 'form.allotBoxCount', 'allotBoxNum', 'allotMainNum', 'allotTaxAmount',
        'allotNoTaxAmount', 'allotTax', 'lossGoodsCount', 'lossBoxCount', 'lossBoxNum', 'lossMainNum', 'lossTaxAmount', 'lossNoTaxAmount', 'lossTax',
        'overGoodsCount', 'overBoxCount', 'overBoxNum', 'overMainNum', 'overTaxAmount', 'overNoTaxAmount', 'overTax', 'allotBoxCount', 'emptyBoxTaxAmount',
        'returnBoxTaxAmount', 'receiveAmount', 'receiptAmount', 'fuckNum', 'boxUnitId'
      ]
      const auxiliaryList = ['boxNum', 'fuckNum']
      columns.forEach((column, index) => {
        if (summaryList.includes(column.property)) {
          sums[index] = this.sum(column.property).toFixed(2)
          selectSumList[index] = this.selectSum(column.property).toFixed(2)
        } else if (auxiliaryList.includes(column.property)) {
          const sum = this.sumAuxiliaryCount('boxNum', 'mainNum')
          const selectSum = this.sumSelectAuxiliaryCount('boxNum', 'mainNum')
          sums[index] = sum
          selectSumList[index] = selectSum
        }
      })

      return [selectSumList, sums]
    },
    formatNum: function (num, n = 6) {
      n = n ? parseInt(n) : 0
      if (n <= 0) {
        return Math.round(num)
      }
      num = Math.round(num * Math.pow(10, n)) / Math.pow(10, n) //四舍五入
      num = Number(num).toFixed(n) //补足位数
      return num
    },
    printPd() {
      if (this.dict.t_sales_order_save_order_status_is_allow_print[0].value == '0' && this.crud.order.orderStatus === 'SAVE') {
        this.$message.error('保存状态单据不允许打印')
        return
      }
      if (this.crud.order.isPrint) {
        this.$confirm('销售单已打印，请确认是否重复打印', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.preView()
        })
      } else {
        this.crud.preView()
        this.crud.order.isPrint = 1
      }
      // setTimeout(()=>{console.log('=========='),this.crud.refresh()},3000)
    },
    detailJump(type) {
      if (this.idList.length) {
        if (type === 'up') {
          const index = this.idList.indexOf(this.crud.order.id)
          if (index !== 0) {
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.replace({ path: `/redirect/sale/salesorderDetail/${this.idList[index - 1]}?idDate=${this.idDate}&isExceed=${this.isExceed}` })
          } else {
            this.$message.error('没有更多数据了')
          }
        } else {
          const index = this.idList.indexOf(this.crud.order.id)

          if (index !== this.idList.length - 1) {
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.replace({ path: `/redirect/sale/salesorderDetail/${this.idList[index + 1]}?idDate=${this.idDate}&isExceed=${this.isExceed}` })
          } else {
            this.$message.error('没有更多数据了')
          }
        }
      }
    },
    addPromotionList(val) {
      if (this.crud.data[val.index].id) {
        this.delRows([this.crud.data[val.index].id])
      }

      this.crud.data.splice(val.index, 1, ...val.data)
      this.showQueryGoods = false
      this.rowIndex = -1
    },
    toUnAccept(id) {
      this.crud.acceptLoading = true
      const ids = [id]
      if (this.crud.order.type == 1) {
        this.$confirm('是否清空应收日期', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
          this.crud.crudMethod.unAccept({ ids, isCleanReceiveDate: 1 }).then(() => {
            this.crud.acceptLoading = false
            this.crud.resetForm()
            Vue.prototype.$message.success('取消验收成功')
            this.crud.refresh()
          })
        }).catch(() => {
          this.crud.crudMethod.unAccept({ ids, isCleanReceiveDate: 0 }).then(() => {
            this.crud.acceptLoading = false
            this.crud.resetForm()
            Vue.prototype.$message.success('取消验收成功')
            this.crud.refresh()
          })
        })
        return
      }
      this.crud.crudMethod.unAccept({ ids, isCleanReceiveDate: 0 }).then(() => {
        this.crud.acceptLoading = false
        this.crud.resetForm()
        Vue.prototype.$message.success('取消验收成功')
        this.crud.refresh()
      })
    },
    append() {
      this.toAdd()
    },
    isPromotion() {
      // if (this.$refs.table.selection.every(item => item.promotionGroupKey)) {
      //   this.$message.error('满赠商品不允许拆分')
      //   return
      // }
      this.$refs.table.selection.forEach(item => {
        this.$set(item, 'splitBoxNum', 0)
        this.$set(item, 'splitMainNum', 0)
        this.$set(item, 'splitGoodsCount', 0)
      })
      this.toSplitShow = true
    },
    isEmptyBox(row) {
      return !(row.isEmptyBoxAdd == '1')
    },
    submitRecycle() {
      const data = {
        orderId: this.crud.order.id,
        detailList: this.recycleData
      }
      this.recycleLoading = true
      crudBasSaleSystem.recycle(data).then(res => {
        this.$message.success(res.msg)
        this.toRecycleShow = false
        this.recycleLoading = false
        this.crud.refresh()
      }).catch(err => {
        this.$message.error(err.data.msg)
        this.recycleLoading = false
      })
    },
    submitOnRecycle() {
      const data = {
        orderId: this.crud.order.id
      }
      crudBasSaleSystem.unRecycle(data).then(res => {
        this.$message.success(res.msg)
        this.crud.refresh()
      }).catch(err => {
        this.$message.error(err.msg)
        this.crud.refresh()
      })
    },
    keyDown() {
      //处理异常掉CurrentRow
      setTimeout(() => {
        this.$refs.table.setCurrentRow(this.crud.data[this.rowIndex])
      }, 10)
      try {
        if (this.showAddBatchDialog || this.showQueryGoods) {
          return
        }
        if (event.keyCode === 121) {
          if (this.crud.order.orderStatus !== 'PASS') {
            event.preventDefault()
            this.toAddList()
          }
        }
        //获取当前行
        const elTableRow = this.$refs['table'].$el.getElementsByClassName('current-row')[0]
        //获取当前行数据
        const row = this.$refs.table.store.states.currentRow
        let index, cells
        const list = []
        //过滤搜索框
        if (row !== null) {
          index = row.index
          cells = elTableRow.querySelectorAll('.el-input__inner,.el-textarea__inner')
          cells.forEach(item => {
            if (item.placeholder != '请输入内容搜索') {
              list.push(item)
            }
          })
        } else {
          index = -1
          cells = elTableRow.querySelectorAll('.el-input__inner,.el-textarea__inner')
        }
        //判断是否手工点击过
        if (list[this.columnIndex] !== document.activeElement) {
          for (let i = 0; i < list.length; i++) {
            if (list[i] === document.activeElement) {
              this.columnIndex = i
              break
            }
          }
        }
        if (event.keyCode === 39) {
          if (this.columnIndex < list.length - 1) {
            this.columnIndex++
          }
          list[this.columnIndex].focus()
          setTimeout(() => {
            list[this.columnIndex].select()
          }, 10)
        } else if (event.keyCode === 40) {
          if (this.crud.data[index + 1] === undefined) {
            this.toAdd()
            setTimeout(() => {
              this.rowIndex = index + 1
              this.$refs.table.setCurrentRow(this.crud.data[this.rowIndex])
              setTimeout(() => {
                cells = this.$refs['table'].$el.querySelectorAll('.current-row')[0].querySelectorAll('.el-input__inner,.el-textarea__inner')
                const list = []
                cells.forEach(item => {
                  if (item.placeholder != '请输入内容搜索') {
                    list.push(item)
                  }
                })

                list[0].focus()
              }, 10)
            }, 10)
          } else {
            this.rowIndex = index + 1
            this.$refs.table.setCurrentRow(this.crud.data[this.rowIndex])
            setTimeout(() => {
              cells = this.$refs['table'].$el.querySelectorAll('.el-input__inner,.el-textarea__inner')
              const list = []
              cells.forEach(item => {
                if (item.placeholder != '请输入内容搜索') {
                  list.push(item)
                }
              })
              list[this.columnIndex].focus()
              setTimeout(() => {
                list[this.columnIndex].select()
              }, 10)
            }, 150)
          }
        } else if (event.keyCode === 38) {
          if (index > 0) {
            this.rowIndex = index - 1
            setTimeout(() => {
              this.$refs.table.setCurrentRow(this.crud.data[this.rowIndex])
              cells = this.$refs.table.$el.querySelectorAll('.el-input__inner,.el-textarea__inner')
              const list = []
              cells.forEach(item => {
                if (item.placeholder != '请输入内容搜索') {
                  list.push(item)
                }
              })
              var dom = this.$refs.table.bodyWrapper
              this.$nextTick(() => {
                dom.scrollTo(0, (index - 1) * 29)
              })
              list[this.columnIndex].focus()
              setTimeout(() => {
                list[this.columnIndex].select()
              }, 10)
            }, 10)
          }
        } else if (event.keyCode === 37) {
          if (this.columnIndex > 0) {
            this.columnIndex--
          }
          list[this.columnIndex].focus()
          setTimeout(() => {
            list[this.columnIndex].select()
          }, 10)
        } else if (event.keyCode === 13) {
          if (list[this.columnIndex] == document.activeElement) {
            if (list[this.columnIndex].placeholder === '请输入商品') {
              this.queryGoods = {
                keyword: list[this.columnIndex].value,
                index: this.rowIndex,
                ignoreGoodsTagNames: '回瓶回箱,瓶盖'
              }
              this.showQueryGoods = true
            } else {
              list[this.columnIndex].blur()
            }
          } else {
            list[this.columnIndex].focus()
          }
        }
        if (event.keyCode === 122) {
          event.preventDefault()
          event.returnValue = !event.returnValue
          this.showPriceDetail(row)
        }
      } catch (e) {

      }
    },
    highlight(row) {
      return row.taxPrice > row.oldTaxPrice ? 'blue' : 'green'
    }
  }
}

</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}

.cu-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-top: 20px;
}

.contextmenu__item {
  display: block;
  line-height: 34px;
  text-align: center;
}

.contextmenu__item:not(:last-child) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.menu {
  position: absolute;
  background-color: #fff;
  width: 100px;
  /*height: 106px;*/
  font-size: 12px;
  color: #444040;
  border-radius: 4px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border: 1px solid #000000;
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  white-space: nowrap;
  z-index: 1000;
}

.contextmenu__item:hover {
  cursor: pointer;
  background: #66b1ff;
  border-color: #66b1ff;
  color: #fff;
}

.red {
  color: red;
}

.blue {
  color: blue;
}

.green {
  color: #0b9c54
}
</style>
